package com.hsmw.api.controller.forman;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hsmw.api.config.jwt.CurrentHsmwUserUtils;
import com.hsmw.api.config.jwt.LoginUser;
import com.htn.common.core.util.ErrorCodeUtil;
import com.hsmw.api.controller.pub.TencentPushUtils;
import com.hsmw.api.controller.pub.WebSocket;
import com.hsmw.api.mapper.*;
import com.hsmw.api.service.*;
import com.hsmw.api.utils.GaoDeInfoUtils;
import com.hsmw.api.utils.PlaceAnOrderUtils;
import com.hsmw.api.vo.*;
import com.hsmw.common.base.*;
import com.htn.common.core.base.BusinessType;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.*;
import com.htn.common.core.enums.ExamineTypeEnum;
import com.hsmw.api.utils.CommonUtils;
import com.htn.common.core.util.SendSmsUtil;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.*;
import com.hsmw.domain.vo.*;
import com.hsmw.domain.vo.DriverInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.htn.common.core.constant.CommonConstants.ResponseStatus.*;

@Api(tags = "工长端相关接口表")
@RestController
@RequestMapping(value = "/api/forman")
public class HsmwFormanController extends BaseController<HsmwUserService, HsmwUser> {

    @Autowired
    private CurrentHsmwUserUtils currentHsmwUserUtils;


    @Autowired
    private HsmwOrderService  hsmwOrderService;

    @Autowired
    private HsmwOrderVehicleRelationService hsmwOrderVehicleRelationService;

    @Autowired
    private HsmwOrderVehicleRequestService hsmwOrderVehicleRequestService;

    @Autowired
    private  HsmwUserDriverService  hsmwUserDriverService;



    @Autowired
    private  HsmwDriverUserService  hsmwDriverUserService;

    @Autowired
    private HsmwDriverNewsService  hsmwDriverNewsService;


    @Autowired
    private HsmwVehicleService   hsmwVehicleService;


    @Autowired
    private HsmwForcemanAddressService  hsmwForcemanAddressService;

    @Autowired
    private HsmwItemService   hsmwItemService;


    @Autowired
    private HsmwPictureService   hsmwPictureService;


    @Autowired
    private HsmwAuditService   hsmwAuditService;


    @Autowired
    private HsmwVolumeRecordService   hsmwVolumeRecordService;


    @Autowired
    private HsmwComplainService   hsmwComplainService;

    @Autowired
    private HsmwLeasingCompanyRuleService hsmwLeasingCompanyRuleService;

    @Autowired
    private HsmwConcretePlantInfoMapper hsmwConcretePlantInfoMapper;
    @Autowired
    private HsmwConstructionPositionService hsmwConstructionPositionService;

    @Autowired
    private HsmwConcreteOperateRecordService hsmwConcreteOperateRecordService;

    @Autowired
    private HsmwPushInfoService hsmwPushInfoService;

    @Autowired
    private HsmwPumpOperateRecordService hsmwPumpOperateRecordService;


    @Autowired
    private HsmwLeasingCompanyService hsmwLeasingCompanyService;

    @Autowired
    private HsmwItemConstructionPositionService hsmwItemConstructionPositionService;

    @Autowired
    private HsmwOrderMapper hsmwOrderMapper;

    @Autowired
    private HsmwOrderVehicleRequestMapper hsmwOrderVehicleRequestMapper;

    @Autowired
    private PlaceAnOrderUtils placeAnOrderUtils;

    @Autowired
    private HsmwForcemanItemMapper  hsmwForcemanItemMapper;

    @Autowired
    private HsmwExamineRecordMapper hsmwExamineRecordMapper;



    @Autowired
    private HsmwHtnUserService hsmwHtnUserService;


    @Autowired
    private HsmwPmUserService hsmwPmUserService;


    @Autowired
    private HsmwUserService hsmwUserService;


    @Autowired
    private HsmwDictDataService hsmwDictDataService;


    @Autowired
    private HsmwOrderRemarkMapper hsmwOrderRemarkMapper;


    @Autowired
    private HsmwRecentConcreteMapper hsmwRecentConcreteMapper;

    @Autowired
    private HsmwItemLinkmanMapper  hsmwItemLinkmanMapper;

    @Autowired
    private HsmwVehicleMapper hsmwVehicleMapper;

    @Autowired
    private HsmwItemLinkmanRelationMapper hsmwItemLinkmanRelationMapper;

    @Autowired
    private HsmwReceiveOrderPriceMapper hsmwReceiveOrderPriceMapper;
    @Autowired
    private HsmwReceiveSubsidyPriceMapper hsmwReceiveSubsidyPriceMapper;

    @Autowired
    private HsmwInviteRecordService hsmwInviteRecordService;

    @Autowired
    private HsmwInviteRecordMapper hsmwInviteRecordMapper;

    @Autowired
    private HsmwVehicleCollectMapper hsmwVehicleCollectMapper;

    @Autowired
    private WebSocket webSocket;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HsmwItemConcreteRelationService hsmwItemConcreteRelationService;


    @Autowired
    private HsmwBanDriverService hsmwBanDriverService;


    @Value(value = "${sms.appKey}")
    private String appKey;
    @Value(value = "${sms.channel}")
    private String channel;
    @Value(value = "${sms.smsSign}")
    private String smsSign;
    @Value(value = "${sms.appId}")
    private int appId;
    @Value(value = "${sms.invitedSuccess}")
    private int invitedSuccess;
    @Value(value = "${sms.processNotice}")
    private int processNotice;

    @Value(value = "${sms.driverChangeWorkStatus}")
    private int driverChangeWorkStatus;

    @Value(value = "${sms.driverRemoveVehicle}")
    private int driverRemoveVehicle;

    @Value(value = "${sms.driverChangeVehicle}")
    private int driverChangeVehicle;





    /**
     * 获取工长所在项目 绑定的 搅拌站列表
     *
     * @param
     * @return
     */
    @Log(title = "工长首页   获取工长所在项目 绑定的搅拌站列表和其他状态", businessType = BusinessType.QUERY)
    @ApiOperation(value = "工长首页   获取工长所在项目 绑定的搅拌站列表和其他状态 ", notes = "获取工长所在项目 绑定的 搅拌站列表", produces = "application/json")
    @PostMapping("/getConcretePlantList")
    public DataResponse getConcretePlantList() {
        try {
            LoginUser user = currentHsmwUserUtils.getCurrentUserInfo();
            HsmwHtnUser usernow =hsmwHtnUserService.getById(user.getId());
            String foremanType =  usernow.getForemanType();

            HsmwItem itemInfo = hsmwItemService .getHsmwItemById(usernow.getItemId());
            List<HsmwConcretePlantInfo> plantInfos = new ArrayList<>();
            //如果角色 类型是工长那么查询 该工长指定项目下面绑定的搅拌站
            HashMap result = new HashMap();
            HashMap param = new HashMap();
            if(UserTypeEnum.VISITOR.getValue().equals(usernow.getType())){
                param.put("userId",user.getId());
                plantInfos = hsmwConcretePlantInfoMapper.selectRetailerPlantList(param);
            }
            if(CommonConstants.FORE_TYPE_1.equals(foremanType) && StringUtils.isNotNull(itemInfo)){
                param.put("itemId",itemInfo.getId());
                plantInfos = hsmwConcretePlantInfoMapper.selectForemanPlantList(param);
            }else {
                param.put("userId",user.getId());
                plantInfos = hsmwConcretePlantInfoMapper.selectRetailerPlantList(param);
            }
            if(!UserTypeEnum.VISITOR.getValue().equals(usernow.getType())){
                for (HsmwConcretePlantInfo info :plantInfos){
                    HashMap calculateParam = new HashMap();
                    calculateParam.put("origin", itemInfo.getLng()+","+itemInfo.getLat());
                    calculateParam.put("destination", info.getLng()+","+info.getLat());
                    Long mapTimeAndDistance = GaoDeInfoUtils.calculateDistance(calculateParam);
                    double distence = mapTimeAndDistance / 1000;
                    System.err.println("距离--->" + distence);
                    info.setConcretePlantDistance(StringUtils.isNull(distence)? 0L:distence);
                }
                result.put("ifSelfChoose",itemInfo.getIfSelfChoose());
                result.put("foremanType",foremanType);
                result.put("itemId",itemInfo.getId());
                result.put("itemLng",itemInfo.getLng());
                result.put("itemLat",itemInfo.getLat());
                result.put("itemName",itemInfo.getName());
                result.put("itemPosition",itemInfo.getPosition());
            }
            result.put("plantList",plantInfos);

            return  new DataResponse(result);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL," 获取工长所在项目 绑定的搅拌站列表和其他状态失败，请联系管理员！");
        }
    }


    /**
     * 工长端创建订单 2.0
     *
     * @param
     * @return
     */
    @Log(title = "混天凝APP端创建或修改订单 工长创建订单 只有 company 和concrete 和 foreman 角色可以下单", businessType = BusinessType.INSERT)
    @ApiOperation(value = "混天凝APP端创建或修改订单 工长创建订单  只有 company 和concrete 和 foreman  俩角色可以下单", notes = "工长端创建或修改订单", produces = "application/json")
    @PostMapping("/createOrUpdateOrder")
    public DataResponse createOrderAsForman(@RequestBody HsmwOrderVO hsmwOrderVO) {
        try {
            LoginUser user = currentHsmwUserUtils.getCurrentUserInfo();
            HsmwHtnUser usernow =hsmwHtnUserService.getById(user.getId());
            if(StringUtils.isNotBlank(hsmwOrderVO.getItemId())){
                boolean flag = hsmwItemService.checkItemIfExists(hsmwOrderVO.getItemId());
                if(!flag){
                    return new DataResponse(ITEM_NOT_EXISTS, "该项目不存在！");
                }
            }
            if (StringUtils.isNotBlank(hsmwOrderVO.getLinkmanId()) && StringUtils.isNotBlank(hsmwOrderVO.getLinkmanType())){
                if(LinkmanTypeEnum.LINKMAN.getValue().equals(hsmwOrderVO.getLinkmanType())){
                    List<HsmwItemLinkman> result=hsmwItemLinkmanMapper.selectList(new LambdaQueryWrapper<HsmwItemLinkman>()
                            .eq(HsmwItemLinkman::getId,hsmwOrderVO.getLinkmanId()));
                    if(CollectionUtil.isEmpty(result)){
                        return new DataResponse(LINKMAN_NOT_EXISTS, "该联系人不存在");
                    }
                }
                if(LinkmanTypeEnum.FOREMAN.getValue().equals(hsmwOrderVO.getLinkmanType())|| LinkmanTypeEnum.PROJECTMAN.getValue().equals(hsmwOrderVO.getLinkmanType())){
                   List<HsmwForcemanItem > result = hsmwForcemanItemMapper.selectList(new LambdaQueryWrapper<HsmwForcemanItem>()
                           .eq(HsmwForcemanItem::getForcemanId,hsmwOrderVO.getLinkmanId())
                           .eq(HsmwForcemanItem::getItemId,hsmwOrderVO.getItemId()));
                    if(CollectionUtil.isEmpty(result)){
                        return new DataResponse(LINKMAN_NOT_EXISTS, "该联系人不存在");
                    }
                }
                if(StringUtils.isNotNull(hsmwOrderVO.getConcretePlantId())){
                    //查询 项目和搅拌站的关联关系是否还存在
                    List<HsmwItemConcreteRelation> relations = hsmwItemConcreteRelationService.list(new LambdaQueryWrapper<HsmwItemConcreteRelation>()
                            .eq(HsmwItemConcreteRelation::getConcreteId,hsmwOrderVO.getConcretePlantId())
                            .eq(HsmwItemConcreteRelation::getItemId,hsmwOrderVO.getItemId()));
                    if(CollectionUtil.isEmpty(relations)){
                        return new DataResponse(CONCRETE_NOT_EXISTS, "该搅拌站已经不是该项目的混凝土供应方");
                    }
                }

            }
            //保存订单信息
            return hsmwOrderService.saveConcreteOrderInfo(hsmwOrderVO,usernow.getForemanType());
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"创建订单失败，请联系管理员！");
        }
    }

    /**
     * 工长端创建订单 2.0
     *
     * @param
     * @return
     */
    @Log(title = "混天凝app修改订单的时间或者施工部位", businessType = BusinessType.INSERT)
    @ApiOperation(value = "混天凝app修改订单的时间或者施工部位 ", notes = "混天凝app修改订单的时间或者施工部位", produces = "application/json")
    @PostMapping("/updateOrderInfo")
    public DataResponse updateOrderInfo(@RequestBody OrderUpdateVO orderUpdateVO) {
        try {
            return hsmwOrderService.updateOrderInfo(orderUpdateVO);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"混天凝app修改订单的时间失败，请联系管理员！");
        }
    }




    /**
     * 创建或修改订单 查询常用的车辆桥数、节臂数
     *
     * @param
     * @return
     */
    @Log(title = "创建或修改订单 查询常用车辆属性信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "创建或修改订单 查询常用车辆属性信息", notes = "创建或修改订单 查询常用车辆属性信息", produces = "application/json")
    @PostMapping("/getVehicleInfo")
    public DataResponse getVehicleInfo() {
        try {

            HashMap result = new HashMap();
            String   axis= hsmwVehicleMapper.findArmAixs();
            String  armSengments = hsmwVehicleMapper.findArmSegments();
            result.put("axis",axis);
            result.put("armSengments",armSengments);
            return new DataResponse(result);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"创建或修改订单 查询常用的备注失败，请联系管理员！");
        }
    }




    /**
     * 创建或修改订单 查询常用的备注
     *
     * @param
     * @return
     */
    @Log(title = "创建或修改订单 查询常用的备注", businessType = BusinessType.INSERT)
    @ApiOperation(value = "创建或修改订单 查询常用的备注", notes = "创建或修改订单 查询常用的备注", produces = "application/json")
    @PostMapping("/getRecentRemark")
    public DataResponse getRecentRemark() {
        try {
            LoginUser currentUser = currentHsmwUserUtils.getCurrentUserInfo();
            HashMap param = new HashMap();
            param.put("userId",currentUser.getId());

            List<HsmwOrderRemark > orderRemarks =hsmwOrderRemarkMapper.selectRemarkList(param);
            if(CollectionUtil.isEmpty(orderRemarks)){
                orderRemarks= new ArrayList<>();
            }
            return new DataResponse(orderRemarks);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"创建或修改订单 查询常用的备注失败，请联系管理员！");
        }
    }


    /**
     * 创建或修改订单 查询常用的备注
     *
     * @param
     * @return
     */
    @Log(title = "创建或修改订单 查询常用的标号", businessType = BusinessType.INSERT)
    @ApiOperation(value = "创建或修改订单 查询常用的混凝土标号", notes = "创建或修改订单 查询常用的混凝土标号", produces = "application/json")
    @PostMapping("/getRecentConcreteNum")
    public DataResponse getRecentConcreteNum() {
        try {
            //字典项中的混凝土标号
            List<HsmwDictData> concreteNus = hsmwDictDataService.list(new LambdaQueryWrapper<HsmwDictData>()
                    .eq(HsmwDictData::getDictType,CommonConstants.HTN_CONCRETE)
                    .orderByAsc(HsmwDictData::getDictSort));
            List<HsmwRecentConcrete> dictConcreteList = new ArrayList<>();
            for(HsmwDictData data :concreteNus){
                HsmwRecentConcrete concrete = new HsmwRecentConcrete();
                concrete.setConcreteNum(data.getDictLabel());
                dictConcreteList.add(concrete);
            }
            LoginUser currentUser = currentHsmwUserUtils.getCurrentUserInfo();
            List<HsmwRecentConcrete > concreteList =hsmwRecentConcreteMapper.selectList(new LambdaQueryWrapper<HsmwRecentConcrete>()
                    .eq(HsmwRecentConcrete::getUserId,currentUser.getId())
                    .orderByDesc(HsmwRecentConcrete::getCreateTime));
            if(CollectionUtil.isEmpty(concreteList)){
                concreteList= new ArrayList<>();
            }
            concreteList.addAll(dictConcreteList);
            sortObjectList(concreteList);
            return new DataResponse(concreteList);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"创建或修改订单 查询常用的标号失败，请联系管理员！");
        }
    }

    private void sortObjectList(List<HsmwRecentConcrete > listOut) {
        Collections.sort(listOut, new Comparator<HsmwRecentConcrete>() {
        @Override
            public int compare(HsmwRecentConcrete o1, HsmwRecentConcrete o2) {
                return o1.getConcreteNum().compareTo(o2.getConcreteNum());//降序
            }
        });
    }
    /**
     * 创建或修改订单 查询常用的备注
     *
     * @param
     * @return
     */
    @Log(title = "混天凝app新增常用的标号", businessType = BusinessType.INSERT)
    @ApiOperation(value = "混天凝app新增常用的标号", notes = "混天凝app新增常用的标号", produces = "application/json")
    @PostMapping("/addRecentConcreteNum")
    public DataResponse getRecentConcreteNum(String concreteNum) {
        try {
            HsmwRecentConcrete hsmwRecentConcrete =new HsmwRecentConcrete();
            hsmwRecentConcrete.setConcreteNum(concreteNum);
            LoginUser currentUser = currentHsmwUserUtils.getCurrentUserInfo();
            hsmwRecentConcrete.setUserId(currentUser.getId());
            hsmwRecentConcreteMapper.insert(hsmwRecentConcrete);
            return new DataResponse();
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"混天凝app新增常用的标号失败，请联系管理员！");
        }
    }




    /**
     * 完善工长信息
     *
     * @param
     * @return
     */
    @Log(title = "完善工长信息 工长分为:1. 正常工长;0: 散户", businessType = BusinessType.QUERY)
    @ApiOperation(value = "完善工长信息 工长分为:1. 正常工长;0: 散户", notes = "完善工长信息", produces = "application/json")
    @PostMapping("/updateForemanInfo")
    public DataResponse updateForemanInfo(@RequestBody ForemanInfoVO foremanInfoVO) {
        try {
            LoginUser currentUser = currentHsmwUserUtils.getCurrentUserInfo();
            List<HsmwItem> itemInfos = hsmwItemService.list(new LambdaQueryWrapper<HsmwItem>()
                    .eq(HsmwItem::getCreateUser,currentUser.getId()));
            if(CollectionUtil.isNotEmpty(itemInfos)){
                return new DataResponse(CommonConstants.ResponseStatus.FAIL,"您已经在申请项目中，不能再申请成为工长！");
            }
            List<HsmwAudit> audits =hsmwAuditService.list(new LambdaQueryWrapper<HsmwAudit>()
                    .eq(HsmwAudit::getUserId,currentUser.getId()));
            if(StringUtils.isListNotNull(audits)){
                return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您正在认证司机身份，不能再申请成为工长！");
            }
            HsmwHtnUser user = new HsmwHtnUser();
            user.setId(currentUser.getId());
            user.setName(foremanInfoVO.getName());
            if(StringUtils.isNotBlank(foremanInfoVO.getItemIdentifyNum())){
                List<HsmwItem> items =hsmwItemService.list(new LambdaQueryWrapper<HsmwItem>()
                        .eq(HsmwItem::getItemIdentifyNum,foremanInfoVO.getItemIdentifyNum()));
                if(CollectionUtil.isEmpty(items)){
                    return  DataResponse.failure(CommonConstants.ResponseStatus.FAIL.getCode(),"您输入的项目识别码不存在请重新输入！");
                }else{
                    HsmwItem item= items.get(0);
                    user.setForemanType(CommonConstants.FORE_TYPE_1);
                    user.setType(UserTypeEnum.FOREMAN.getValue());
                    HsmwPmUser pm = hsmwPmUserService.getById(item.getCreateUser());
                    if(StringUtils.isNull(pm)){
                        return new DataResponse(CommonConstants.ResponseStatus.FAIL,"您输入的项目识别码不存在请重新输入！");
                    }
                    //保存信息到 项目和工长的关联表中
                    HsmwForcemanItem forcemanItem = new HsmwForcemanItem();
                    forcemanItem.setItemId(item.getId());
                    forcemanItem.setForcemanId(user.getId());
                    hsmwForcemanItemMapper.insert(forcemanItem);

                    //新增系统消息
                    String msg = "您创建的项目已审核通过，可以邀请工长加入项目了，详情请点击himowang.com/sjd";
                    HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
                    hsmwDriverNews.setUserId(item.getCreateUser());
                    hsmwDriverNews.setMessage(msg);
                    hsmwDriverNews.setAlreadyRead("0");
                    hsmwDriverNewsService.save(hsmwDriverNews);
                    SendSmsUtil.sendBizOrderSmsCode(appId, appKey, currentUser.getName(),invitedSuccess, smsSign, pm.getUsername());
                    hsmwHtnUserService.updateById(user);
                    return new DataResponse();
                }
            }else {
                user.setForemanType(CommonConstants.FORE_TYPE_0);
                user.setType(UserTypeEnum.FOREMAN.getValue());
                user.setAuditStatus(AuditStatusEnum.UNRECEIVED.getValue());
                hsmwHtnUserService.updateById(user);
                HsmwExamineRecord record = new HsmwExamineRecord();
                record.setAuditId(user.getId());
                record.setAuditType(ExamineTypeEnum.TYPE_DRIVER.getValue());
                record.setName(user.getName());
                record.setUserId(user.getId());
                record.setReadFlag(false);
                record.setUsername(currentUser.getUsername());
                record.setMessage("有用户申请散户");
                hsmwExamineRecordMapper.insert(record);

                return new DataResponse();
            }
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"完善工长信息，请联系管理员！");
        }

    }


    /**
     * 常用地址信息的增删改查
     *
     * @param
     * @return
     */
    @Log(title = "常用地址信息的增加", businessType = BusinessType.INSERT)
    @ApiOperation(value = "常用地址信息的增加  详细地址，地址标题，经度，纬度 不能为空", notes = "常用地址信息的增加", produces = "application/json")
    @PostMapping("/address/add")
    public DataResponse vehicleLicenceOCR(@RequestBody HsmwForcemanAddress hsmwForcemanAddress) {
        try {
            LoginUser user = currentHsmwUserUtils.getCurrentUserInfo();
            HsmwHtnUser usernow =hsmwHtnUserService.getById(user.getId());
            if(StringUtils.isBlank(hsmwForcemanAddress.getAddrDetail())){
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "您输入的详细地址为空，请重新输入！");
            }
            if( StringUtils.isBlank(hsmwForcemanAddress.getAddrTitle())){
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "您输入的地址标题为空，请重新输入！");
            }
            if( StringUtils.isBlank(hsmwForcemanAddress.getLng())){
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "您输入的经度为空，请重新输入！");
            }
            if( StringUtils.isBlank(hsmwForcemanAddress.getLat())){
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "您输入的纬度为空，请重新输入！");
            }
            HsmwHtnUser hsmwUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
            hsmwForcemanAddress.setUserId(hsmwUser.getId());
            hsmwForcemanAddressService.save(hsmwForcemanAddress);
            return new DataResponse();
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"新增常用地址信息异常，请联系管理员！");
        }
    }
    /**
     * 常用地址信息的增删改查
     *
     * @param
     * @return
     */
    @Log(title = "常用地址信息的修改", businessType = BusinessType.QUERY)
    @ApiOperation(value = "常用地址信息的修改", notes = "常用地址信息的修改", produces = "application/json")
    @PostMapping("/address/update")
    public DataResponse updateAddressInfo(@RequestBody HsmwForcemanAddress hsmwForcemanAddress) {
        try {
            LoginUser loginUser = currentHsmwUserUtils.getCurrentUserInfo();
            HsmwHtnUser usernow =currentHsmwUserUtils.getCurrentHtnUserInfo();
            if(StringUtils.isBlank(hsmwForcemanAddress.getId())){
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "您输入的地址ID为空，请重新输入！");
            }

            hsmwForcemanAddress.setUpdateUser(loginUser.getId());
            hsmwForcemanAddressService.updateById(hsmwForcemanAddress);
            return new DataResponse();
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"修改常用地址信息异常，请联系管理员！");
        }
    }

    /**
     * 常用地址信息的增删改查
     *
     * @param
     * @return
     */
    @ApiOperation(value = "常用地址信息的删除", notes = "常用地址信息的删除", produces = "application/json")
    @PostMapping("/address/delete")
    public DataResponse deleteAddressInfo(@RequestBody HsmwForcemanAddress hsmwForcemanAddress) {
        try {
            LoginUser loginUser = currentHsmwUserUtils.getCurrentUserInfo();
            HsmwHtnUser usernow =currentHsmwUserUtils.getCurrentHtnUserInfo();

            if(StringUtils.isBlank(hsmwForcemanAddress.getId())){
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "您输入的地址ID为空，请重新输入！");
            }
            hsmwForcemanAddressService.removeById(hsmwForcemanAddress.getId());
            return new DataResponse();
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"修改常用地址信息异常，请联系管理员！");
        }
    }


    /**
     * 常用地址信息的增删改查
     *
     * @param
     * @return
     */
    @Log(title = "项目位置信息查询", businessType = BusinessType.QUERY)
    @ApiOperation(value = "项目位置信息查询", notes = "常用地址信息的查询", produces = "application/json")
    @PostMapping("/getItemAddressInfo")
    public DataResponse getItemAddressInfo() {
        try {
            LoginUser loginUser = currentHsmwUserUtils.getCurrentUserInfo();
            HsmwHtnUser hsmwHtnUser =hsmwHtnUserService.getById(loginUser.getId());
            HsmwItem item =new HsmwItem();
            if(StringUtils.isNotBlank(hsmwHtnUser.getForemanType()) && CommonConstants.FORE_TYPE_1.equals(hsmwHtnUser.getForemanType())) {
                item = hsmwItemService.getHsmwItemById(hsmwHtnUser.getItemId());
            }
            return new DataResponse(item);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"项目位置信息查询异常，请联系管理员！");
        }
    }


    /**
     * 常用地址信息的增删改查
     *
     * @param
     * @return
     */
    @Log(title = "常用地址信息的查询", businessType = BusinessType.QUERY)
    @ApiOperation(value = "常用地址信息的查询", notes = "常用地址信息的查询", produces = "application/json")
    @PostMapping("/address/getAddressInfo")
    public DataResponse getAddressInfos() {
        try {
            LoginUser loginUser = currentHsmwUserUtils.getCurrentUserInfo();
            HsmwHtnUser usernow =currentHsmwUserUtils.getCurrentHtnUserInfo();
            LambdaQueryWrapper<HsmwForcemanAddress> lambdaQueryWrapper = new LambdaQueryWrapper<HsmwForcemanAddress>();
            lambdaQueryWrapper.eq(HsmwForcemanAddress::getUserId,loginUser.getId()).last("limit 10");
            List<HsmwForcemanAddress> list =  hsmwForcemanAddressService.list(lambdaQueryWrapper);
            return new DataResponse(list);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"查询常用地址信息异常，请联系管理员！");
        }
    }

    /**
     * 常用地址信息的增删改查
     *
     * @param
     * @return
     */
    @Log(title = "工长创建订单 -查询常用施工部位", businessType = BusinessType.QUERY)
    @ApiOperation(value = "工长创建订单 -查询常用施工部位", notes = "查询常用施工部位", produces = "application/json")
    @PostMapping("/queryRecentsPositionlist")
    public DataResponse getAddressInfo(String itemId) {
        try {
            LoginUser loginUser = currentHsmwUserUtils.getCurrentUserInfo();
            HsmwHtnUser usernow =currentHsmwUserUtils.getCurrentHtnUserInfo();
            List<HsmwItemConstructionPosition> hsmwItemConstructionPositionList = hsmwItemConstructionPositionService.list(new LambdaQueryWrapper<HsmwItemConstructionPosition>()
                    .eq(HsmwItemConstructionPosition::getItemId,itemId).orderByDesc(HsmwItemConstructionPosition::getCreateTime));
            HashMap param =new HashMap();
            param.put("userId",loginUser.getId());
            List<HsmwConstructionPosition> positionList =  hsmwConstructionPositionService.queryRecentPositionlist(param);
            for (HsmwConstructionPosition position : positionList){
                HsmwItemConstructionPosition position1 = new HsmwItemConstructionPosition();
                position1.setPosition(position.getPosition());
                position1.setId(CommonUtils.generateId(position));
                hsmwItemConstructionPositionList.add(position1);
            }

            HashMap result = new HashMap();
            result.put("positionList",hsmwItemConstructionPositionList);
            return new DataResponse(result);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"查询常用施工部位，请联系管理员！");
        }
    }


    /**
     * 常用地址信息的增删改查
     *
     * @param
     * @return
     */
    @Log(title = "企业版 创建订单 -查询常用施工部位", businessType = BusinessType.QUERY)
    @ApiOperation(value = "企业版 创建订单 -查询常用施工部位", notes = "查询常用施工部位", produces = "application/json")
    @PostMapping("/sulfrunQueryRecentsPositionlist")
    public DataResponse sulfrunQueryRecentsPositionlist(String itemId) {
        try {
            LoginUser loginUser = currentHsmwUserUtils.getCurrentUserInfo();
            HsmwHtnUser usernow =currentHsmwUserUtils.getCurrentHtnUserInfo();
            List<HsmwItemConstructionPosition> hsmwItemConstructionPositionList = hsmwItemConstructionPositionService.list(new LambdaQueryWrapper<HsmwItemConstructionPosition>()
                    .eq(HsmwItemConstructionPosition::getItemId,itemId).orderByDesc(HsmwItemConstructionPosition::getCreateTime));
            HashMap param =new HashMap();
            param.put("userId",loginUser.getId());
            List<HsmwConstructionPosition> positionList =  hsmwConstructionPositionService.queryRecentPositionlist(param);
            for (HsmwConstructionPosition position : positionList){
                HsmwItemConstructionPosition position1 = new HsmwItemConstructionPosition();
                position1.setPosition(position.getPosition());
                position1.setId(CommonUtils.generateId(position));
                hsmwItemConstructionPositionList.add(position1);
            }
            HashMap result = new HashMap();
            result.put("positionList",hsmwItemConstructionPositionList);
            return new DataResponse(result);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"查询常用施工部位，请联系管理员！");
        }
    }





    /**
     * @param
     * @return
     */
    @ApiOperation(value = "获取 工长创建订单所需的 字典数据", notes = "获取 工长创建订单所需的 字典数据", produces = "application/json")
    @GetMapping("/getDictData")
    public DataResponse getDictData() {
        LoginUser loginUser = currentHsmwUserUtils.getCurrentUserInfo();
        HsmwHtnUser usernow =currentHsmwUserUtils.getCurrentHtnUserInfo();
        HashMap result = hsmwOrderService.getOrderDictInfo();
        return new DataResponse(result);
    }


    /**
     * 查询订单的实时进度信息
     *
     * @param
     * @return
     */
    @Log(title = "查询订单的实时进度信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查询订单的实时进度信息 orderId 不能为空", notes = "查询订单的实时进度信息", produces = "application/json")
    @PostMapping("/selectOrderProcessInfo")
    public DataResponse selectOrderProcessByOrderId(@RequestBody OrderQueryParam orderQueryParam) {
        LoginUser loginUser = currentHsmwUserUtils.getCurrentUserInfo();
        HsmwHtnUser usernow =currentHsmwUserUtils.getCurrentHtnUserInfo();
        if(StringUtils.isBlank(orderQueryParam.getRelationId())){
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "泵车订单ID不能为空，请重新输入！");
        }
        try {
            HashMap param = new HashMap();
            param.put("relationId",orderQueryParam.getRelationId());
            List<PMGoingOrderVO> list  = hsmwOrderService.selectOrderProcessByOrderId(param);
            PMGoingOrderVO vo = new PMGoingOrderVO();
            if(CollectionUtil.isNotEmpty(list)){
                vo=list.get(0);
            }
            List<HsmwVolumeRecord> records = hsmwVolumeRecordService.list(new LambdaQueryWrapper<HsmwVolumeRecord>()
                    .eq(HsmwVolumeRecord::getRelationId,orderQueryParam.getRelationId()));
            vo.setVolumeRecords(records);
            return new DataResponse(vo);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"获取订单列表失败，请联系管理员！");
        }
    }

    /**
     * 查询订单的实时进度信息
     *
     * @param
     * @return
     */
    @Log(title = "工长端 更新订单的实时进度信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "工长端 更新订单的实时进度信息 orderId 不能为空 ;泵车单ID： relationId 不能为空；当前累计的方量 realTimeVolume 不能为空", notes = "更新订单的实时进度信息", produces = "application/json")
    @PostMapping("/updateRealTimeVolume")
    public DataResponse updateRealTimeVolume(@RequestBody OrderQueryParam orderQueryParam) {
        LoginUser loginUser = currentHsmwUserUtils.getCurrentUserInfo();
        HsmwHtnUser usernow =currentHsmwUserUtils.getCurrentHtnUserInfo();
        if(StringUtils.isBlank(orderQueryParam.getRelationId())){
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "泵车订单ID不能为空，请重新输入！");
        }
        if(StringUtils.isBlank(orderQueryParam.getRealTimeVolume())){
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "订单实时累计方量不能为空，请重新输入！");
        }
        if(StringUtils.isBlank(orderQueryParam.getOrderId())){
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "orderId不能为空，请重新输入！");
        }
        try {
            HsmwOrderVehicleRelation order = new HsmwOrderVehicleRelation();
            order.setRealTimeVolume(orderQueryParam.getRealTimeVolume());
            order.setId(orderQueryParam.getRelationId());
            order.setRealVolumeTime(LocalDateTime.now());
            hsmwOrderVehicleRelationService.updateById(order);
            //记录到方量更新表中
            HsmwVolumeRecord record = new HsmwVolumeRecord();
            record.setRecordTime(LocalDateTime.now());
            record.setRecordVolume(orderQueryParam.getRealTimeVolume());
            record.setRelationId(orderQueryParam.getRelationId());
            record.setOrderId(orderQueryParam.getOrderId());
            record.setCreateTime(LocalDateTime.now());
            hsmwVolumeRecordService.save(record);

            //当实时的放量更新了以后 ，需要给项目经理实时的同步信息
            HsmwOrder orderInfo=hsmwOrderService.getHsmwOrderById(orderQueryParam.getOrderId());
            //只有当真正开始开始干活的时候 才会推送信息
            if(StringUtils.isNotNull(orderInfo.getStartWorkTime())){
                //短信提醒PM的方量更新
                HsmwOrderVehicleRequest request = hsmwOrderVehicleRequestService.getById(order.getOrderVehicleRequestId());
                HsmwConstructionPosition constructionPosition = hsmwConstructionPositionService.getById(request.getPositionId());

                SendSmsUtil.sendBizOrderSmsCode(appId, appKey, constructionPosition.getPosition(),processNotice, smsSign, orderInfo.getCreateUserTel());

            }
            return new DataResponse();
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"更新订单的实时进度信息失败，请联系管理员！");
        }
    }


    /**
     * 取消订单 （需要修改）
     *
     * @param
     * @return
     */
    @Log(title = "混天凝APP  取消订单", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "混天凝APP取消订单", notes = "混天凝APP取消订单", produces = "application/json")
    @PostMapping("/cancelPumpOrder")
    public  DataResponse cancelOrder(@RequestBody OrderCancelVO  orderCancelVO) {
        if(StringUtils.isBlank(orderCancelVO.getType())){
            return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您输入的取消类型为空！");
        }
        return hsmwOrderService.cancelPumpOrder(orderCancelVO);
    }


    /**
     * 搜索关键词位置信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "工长：搜索关键词位置信息 ", notes = "司机提交遇到的问题", produces = "application/json")
    @PostMapping("/searchKeywordsLocateInfo")
    public DataResponse submitProblem(@RequestParam(value = "keyWords")  String  keyWords) {
        try {
            HashMap param = new HashMap();
            param.put("keywords",keyWords);
            List<GaodeSearchEntity> entities = GaoDeInfoUtils.searchKeywordsLocate(param);
            return new DataResponse(entities);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"获取订单详情失败，请联系管理员！");
        }
    }


    /**
     * 搜索关键词位置信息 （改一下）
     *
     * @param
     * @return
     */
    @Log(title = "工长：打电话接口", businessType = BusinessType.QUERY)
    @ApiOperation(value = "工长：打电话接口： 子订单id：orderVehicleRelationId必输 ，订单ID ：orderId 必输；司机电话： driverTelphoneNum ", notes = "司机提交遇到的问题", produces = "application/json")
    @PostMapping("/getVirtualTelephony")
    public DataResponse getVirtualTelephony(@RequestBody  CallVO  callVO) {
        try {
            HsmwHtnUser usernow =currentHsmwUserUtils.getCurrentHtnUserInfo();
            callVO.setForemanLinkTel(usernow.getUsername());
            return  hsmwUserService.getVirtualTelephony(callVO);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"获取订单详情失败，请联系管理员！");
        }
    }


    /**
     * 获取车辆位置 信息
     *
     * @param
     * @return
     */
    @Log(title = "获取车辆信息 车牌号：vehicleNum 必输 itemLng itemLat 必输 ", businessType = BusinessType.QUERY)
    @ApiOperation(value = "获取车辆位置信息：车牌号：vehicleNum 必输 itemLng itemLat 必输 ", notes = "司机提交遇到的问题", produces = "application/json")
    @PostMapping("/getVehicleLocation")
    public DataResponse getVehicleLocation(@RequestBody  VehicleLocationVO  vehicleLocationVO) {
        try {
            Assert.notNull(vehicleLocationVO.getVehicleNum(), "车牌号不能为空");
            HashMap result = new HashMap();
            HsmwVehicle vehicle = hsmwVehicleService.getOne(new LambdaQueryWrapper<HsmwVehicle>()
                    .eq(HsmwVehicle::getVehiclePlate,vehicleLocationVO.getVehicleNum()));
            if(StringUtils.isNotNull(vehicle)){
                if(StringUtils.isNotBlank(vehicle.getImeiNum()) || StringUtils.isNotBlank(vehicle.getIdentifyingCode())){
                    GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(vehicle.getImeiNum(),vehicle.getFlag(),vehicle.getIdentifyingCode());
                    if(StringUtils.isNotNull(entity) && StringUtils.isNotBlank(entity.getGpsLon())){
                        result.put("location",entity.getGpsLon()+","+entity.getGpsLat());
                        result.put("direct",entity.getDirect());
                    }else {
                        result.put("location",vehicle.getMobileLocate());
                        result.put("direct",vehicle.getMobileDirect());
                    }
                }else {
                    result.put("location",vehicle.getMobileLocate());
                    result.put("direct",vehicle.getMobileDirect());
                }
                if(StringUtils.isNotBlank(vehicleLocationVO.getItemLng())){
                    //如果车ID不为空 则查询车量距离项目的距离
                    String vehicleLocalteInfo = null;
                    String destinationLocateInfo = vehicleLocationVO.getItemLng() + "," + vehicleLocationVO.getItemLat();
                    if (StringUtils.isNotBlank(vehicle.getImeiNum()) || StringUtils.isNotBlank(vehicle.getIdentifyingCode())) {
                        GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(vehicle.getImeiNum(),vehicle.getFlag(),vehicle.getIdentifyingCode());
                        if (StringUtils.isNotNull(entity) && StringUtils.isNotBlank(entity.getGpsLon())) {
                            vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
                        }else {
                            vehicleLocalteInfo =vehicle.getMobileLocate();
                        }
                    }else{
                        vehicleLocalteInfo =vehicle.getMobileLocate();
                    }
                    HashMap calculateParam = new HashMap();
                    calculateParam.put("origin", vehicleLocalteInfo);
                    calculateParam.put("destination", destinationLocateInfo);
                    Map<String, Long> mapTimeAndDistance = GaoDeInfoUtils.calculateDistanceDistence(calculateParam);
                    Long distence = 0L;
                    if(StringUtils.isNotNull(mapTimeAndDistance.get("distence"))){
                        distence= mapTimeAndDistance.get("distence") / 1000;
                    }
                    Long time =0L;
                    if(StringUtils.isNotNull(mapTimeAndDistance.get("time"))) {
                        time  =mapTimeAndDistance.get("time");
                    }
                    Date now = new Date();
                    Long reach = now.getTime()+time*1000;
                    Date reachTime = new Date(reach);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    String timeStr = sdf.format(reachTime);
                    result.put("distence",distence);
                    result.put("time",timeStr);
                    String hourTime = timeStr.substring(11);
                    result.put("hourTime",hourTime);
                }
            }
            return  new DataResponse(result);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"获取车辆信息失败，请联系管理员！");
        }
    }



    /**
     * 获取司机个人信息卡片信息
     *
     * @param
     * @return
     */
    @Log(title = "工长：获取司机个人信息卡片信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "工长：获取司机个人信息卡片信息", notes = "获取司机个人信息卡片信息", produces = "application/json")
    @PostMapping("/getDriverTotalInfo/{driverId}")
    public DataResponse getDriverTotalInfo(@PathVariable(value = "driverId")  String  driverId) {
        try {
            HashMap param = new HashMap();
            param.put("driverId",driverId);
            DriveTotalInfoVO  driveTotalInfoVO = hsmwUserDriverService.getDriverTotalInfo(param);
            return new DataResponse(driveTotalInfoVO);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"获取订单详情失败，请联系管理员！");
        }
    }


    /**
     * 查询工长是否有项目
     *
     * @param
     * @return
     */
    @Log(title = "工长：查询工长是否有项目", businessType = BusinessType.QUERY)
    @ApiOperation(value = "工长：查询工长是否有项目： ", notes = "查询工长是否有项目", produces = "application/json")
    @PostMapping("/checkIfExistsitem")
    public DataResponse checkIfExistsitem() {
        try {
            HsmwHtnUser usernow =currentHsmwUserUtils.getCurrentHtnUserInfo();
            HashMap result = new HashMap();
            if(StringUtils.isNotBlank(usernow.getItemId())){
                result.put("auditStatus",usernow.getAuditStatus());
                result.put("itemId",usernow.getItemId());
            }else {
                result.put("itemId",null);
                result.put("auditStatus",usernow.getAuditStatus());
            }
            return  new DataResponse(result);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"查询工长是否有项目失败，请联系管理员！");
        }
    }




    /**
     * 查询订单的实时进度信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "校验订单识别码的信息 vehicleId，identityNum   不能为空 ", notes = "查询车辆的实时订单信息", produces = "application/json")
    @PostMapping("/checkOrderIdAndIdentify")
    public DataResponse checkOrderIdAndIdentify(@RequestBody OrderQueryParam orderQueryParam) {

        if(StringUtils.isBlank(orderQueryParam.getVehicleId())){
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "车辆ID不能为空，请重新输入！");
        }
        if(StringUtils.isBlank(orderQueryParam.getIdentityNum())){
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "订单识别码不能为空，请重新输入！");
        }
        try {
            HashMap result = new HashMap();
            HashMap param = new HashMap();
            param.put("vehicleId",orderQueryParam.getVehicleId());
            List<HsmwOrder> list  = hsmwOrderService.selectOrderByVehicleId(param);
            if(CollectionUtil.isNotEmpty(list)){
                HsmwOrder order  =list.get(0);
                if(order.getIdentityNum() .equals(orderQueryParam.getIdentityNum())){
                    result.put("status","1");
                    result.put("msg","校验通过");
                }else {
                    result.put("status","0");
                    result.put("msg","校验不通过");
                }
            }else{
                result.put("status","0");
                result.put("msg","该车辆没有进行中的订单");
            }
            return new DataResponse(result);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"查询车辆的实时订单信息失败，请联系管理员！");
        }
    }

    /**
     * 查询订单的实时进度信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "查询车辆的实时订单信息 vehicleId 不能为空", notes = "查询车辆的实时订单信息", produces = "application/json")
    @PostMapping("/selectVehicleProcessInfo")
    public DataResponse selectVehicleProcessInfo(@RequestBody OrderQueryParam orderQueryParam) {
        if(StringUtils.isBlank(orderQueryParam.getVehicleId())){
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "车辆ID不能为空，请重新输入！");
        }
        try {
            HashMap param = new HashMap();
            param.put("vehicleId",orderQueryParam.getVehicleId());
            List<PMGoingOrderVO> list  = hsmwOrderService.selectOrderProcessByVehicleId(param);
            PMGoingOrderVO vo = new PMGoingOrderVO();
            if(CollectionUtil.isNotEmpty(list)){
                vo=list.get(0);
            }
            return new DataResponse(vo);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"查询车辆的实时订单信息失败，请联系管理员！");
        }
    }


    /**
     * 查询订单的实时进度信息
     *
     * @param
     * @return
     */
    @Log(title = "工长端  查询车辆的实时订单信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "工长端  查询车辆的实时订单信息 vehicleId 不能为空", notes = "查询车辆的实时订单信息", produces = "application/json")
    @PostMapping("/foremanSelectVehicleProcessInfo")
    public DataResponse foremanSelectVehicleProcessInfo(@RequestBody OrderQueryParam orderQueryParam) {
        if(StringUtils.isBlank(orderQueryParam.getRelationId())){
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "车辆ID不能为空，请重新输入！");
        }
        try {
            HashMap param = new HashMap();
            param.put("relationId",orderQueryParam.getRelationId());
            List<PMGoingOrderVO> list  = hsmwOrderService.selectOrderProcessByOrderId(param);
            PMGoingOrderVO vo = new PMGoingOrderVO();
            if(CollectionUtil.isNotEmpty(list)){
                vo=list.get(0);
            }
            return new DataResponse(vo);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"查询车辆的实时订单信息失败，请联系管理员！");
        }
    }

    /**
     * 二维码 更新订单的实时进度信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "二维码  更新订单的实时进度信息 orderId 不能为空 ;泵车单ID： VehicleRelationId 不能为空；当前累计的方量 realTimeVolume 不能为空", notes = "更新订单的实时进度信息", produces = "application/json")
    @PostMapping("/qrRealTimeVolume")
    public DataResponse qrRealTimeVolume(@RequestBody OrderQueryParam orderQueryParam) {
        System.out.println(orderQueryParam.toString());
        if(StringUtils.isBlank(orderQueryParam.getIdentityNum())){
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "订单识别码不能为空，请重新输入！");
        }
        if(StringUtils.isBlank(orderQueryParam.getOrderId())){
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "订单ID不能为空，请重新输入！");
        }
        if(StringUtils.isBlank(orderQueryParam.getRealTimeVolume())){
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "订单实时累计方量不能为空，请重新输入！");
        }
        if(StringUtils.isBlank(orderQueryParam.getOrderVehicleRelationId())){
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "泵车订单ID不能为空，请重新输入！");
        }
        try {
            HsmwOrder orderInfo = hsmwOrderService.getById(orderQueryParam.getOrderId());
            if (!orderInfo.getIdentityNum().equals(orderQueryParam.getIdentityNum())){
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "订单识别码校验失败，请重新输入！");
            }
            HsmwOrderVehicleRelation order = new HsmwOrderVehicleRelation();
            order.setRealTimeVolume(orderQueryParam.getRealTimeVolume());
            order.setId(orderQueryParam.getOrderVehicleRelationId());
            order.setRealVolumeTime(LocalDateTime.now());
            hsmwOrderVehicleRelationService.updateById(order);
            //记录到方量更新表中
            HsmwVolumeRecord record = new HsmwVolumeRecord();
            record.setRecordTime(LocalDateTime.now());
            record.setRecordVolume(orderQueryParam.getRealTimeVolume());
            record.setRelationId(orderQueryParam.getOrderVehicleRelationId());
            //record.setRecordUser();
            record.setOrderId(orderQueryParam.getOrderId());
            record.setCreateTime(LocalDateTime.now());
            hsmwVolumeRecordService.save(record);
            return new DataResponse();
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"更新订单的实时进度信息失败，请联系管理员！");
        }
    }


    /**
     * 查询工长是否有项目
     *
     * @param
     * @return
     */
    @ApiOperation(value = "工长端：查询可用工长： ", notes = "查询工长是否有项目", produces = "application/json")
    @PostMapping("/selectAviableForeman")
    public DataResponse selectAviableForeman() {
        try {
            HsmwHtnUser usernow =currentHsmwUserUtils.getCurrentHtnUserInfo();
            List<HsmwHtnUser> users = hsmwHtnUserService.list(new LambdaQueryWrapper<HsmwHtnUser>()
                    .ne(HsmwHtnUser::getId,usernow.getId())
                    .eq(HsmwHtnUser::getType,HtnUserTypeEnum.FOREMAN.getValue())
                    .eq(HsmwHtnUser::getEnabled,true));
            List<HashMap> res = new ArrayList<>();
            if(CollectionUtil.isNotEmpty(users)){
                users.stream().forEach(foreman->{
                    HashMap hashMap = new HashMap();
                    hashMap.put("username",foreman.getUsername());
                    hashMap.put("userId",foreman.getId());
                    hashMap.put("name",foreman.getName());
                    res.add(hashMap);
                });
            }
            return  new DataResponse(res);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"查询工长是否有项目失败，请联系管理员！");
        }
    }



    /**
     * 转移订单
     *
     * @param
     * @return
     */
    @ApiOperation(value = "工长：转移订单： ", notes = "转移订单", produces = "application/json")
    @PostMapping("/orderTransfer")
    public DataResponse orderTransfer(@RequestBody OrderTransferVO orderTransferVO) {
        try {
            if(StringUtils.isBlank(orderTransferVO.getOrderId())){
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "订单ID不能为空，请重新输入！");
            }
            if(StringUtils.isBlank(orderTransferVO.getUserId())){
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "工长ID不能为空，请重新输入！");
            }
            HsmwOrder  order = hsmwOrderService.getById(orderTransferVO.getOrderId());
            HsmwHtnUser newForeman = hsmwHtnUserService.getById(orderTransferVO.getUserId());
            order.setCreateUser(newForeman.getId());
            order.setCreateName(newForeman.getName());
            hsmwOrderService.updateById(order);
            return  new DataResponse();
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"工长：转移订单失败，请联系管理员！");
        }
    }


    /**
     * 根据类型查询空闲中的车辆以及距离
     */
    @Log(title = "叫车端首页 查询", businessType = BusinessType.QUERY)
    @ApiOperation(value = "叫车端首页", notes = "叫车端首页", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "车辆类型", name = "vehicleType", dataType = "String"),
            @ApiImplicitParam(value = "车辆型号", name = "vehicleModel", dataType = "String"),
            @ApiImplicitParam(value = "项目经度", name = "itemLng", dataType = "String"),
            @ApiImplicitParam(value = "项目纬度", name = "itemLat", dataType = "String"),
            @ApiImplicitParam(value = "年限", name = "years", dataType = "String"),
            @ApiImplicitParam(value = "节臂数", name = "armSegment", dataType = "String"),
            @ApiImplicitParam(value = "桥数", name = "axis", dataType = "String")
    })
    @PostMapping("/findVehicleCountAndDistance")
    public DataResponse findVehicleCountAndDistance(@RequestBody IdleVehicleQueryVO idleVehicleQueryVO) {
        return  hsmwOrderService.findVehicleCountAndDistance(idleVehicleQueryVO);
    }


    /**
     * 叫车端的投诉信息上报
     */
    @Log(title = "叫车端的投诉信息上报", businessType = BusinessType.INSERT)
    @ApiOperation(value = "叫车端的投诉信息上报", notes = "叫车端的投诉信息上报", produces = "application/json")
    @PostMapping("/addComplainInfo")
    public DataResponse addComplainInfo(@RequestBody HsmwComplain hsmwComplain){

        LoginUser user = currentHsmwUserUtils.getCurrentUserInfo();
        if(StringUtils.isNotBlank(hsmwComplain.getOrderId())){
            HsmwOrderVehicleRelation relation = hsmwOrderVehicleRelationService.getById(hsmwComplain.getOrderId());
            if(StringUtils.isNotBlank(relation.getOrderId())){
                HsmwOrder order = hsmwOrderService.getById(relation.getOrderId());
                hsmwComplain.setItemName(order.getItemName());
            }
        }
        hsmwComplain.setCreateUser(user.getId());
        hsmwComplain.setComplainName(user.getName());
        hsmwComplain.setComplainPhone(user.getUsername());
        hsmwComplainService.save(hsmwComplain);

        if (CollectionUtil.isNotEmpty(hsmwComplain.getPicList())) {
            List<HsmwPicture> pictures = new ArrayList<>();
            List<HashMap> picList = hsmwComplain.getPicList();
            if (null != picList && picList.size() > 0) {
                for (HashMap<String, String> pic : picList) {
                    HsmwPicture temp = new HsmwPicture();
                    temp.setPicPath(pic.get("picPath"));
                    temp.setPicRealPath(pic.get("realPath"));
                    temp.setComplainId(hsmwComplain.getId());
                    temp.setCreateTime(LocalDateTime.now());
                    temp.setPicType(PicTypeEnum.FOREMAN_COMPLAIN.getValue());
                    pictures.add(temp);
                }
            }
            hsmwPictureService.saveBatch(pictures);
        }
        return new DataResponse(SUCCESS,"操作成功");
    }


    /**
     * 空闲车辆列表
     * @return
     * */
    @Log(title = "空闲车辆列表", businessType = BusinessType.QUERY)
    @ApiOperation(value = "空闲车辆列表", notes = "空闲车辆列表", produces = "application/json")
    @PostMapping("/findFreeVehicleAndDriverList")
    public DataResponse findFreeVehicleAndDriverList(@RequestBody QueryFreeParams queryFreeParams) {
        Long start =System.currentTimeMillis();
        HsmwHtnUser currentHtnHsmwUser =currentHsmwUserUtils.getCurrentHtnUserInfo();
        List<IdleVehicleVo> idleVehicleVos = new ArrayList<>();
        HsmwItem hsmwItem = hsmwItemService.getById(currentHtnHsmwUser.getItemId());
        //根据车辆类型 型号 项目所在位置经纬度 查询空闲中的车辆
        List<IdleVehicleVo> vehicleVoList = hsmwVehicleService.findVehicleList(queryFreeParams);
        if (CollectionUtil.isNotEmpty(vehicleVoList)) {
            for (IdleVehicleVo hsmwVehicle : vehicleVoList) {
                String vehicleLocalteInfo = null;
                String destinationLocateInfo = queryFreeParams.getItemLng() + "," + queryFreeParams.getItemLat();
                if (StringUtils.isNotBlank(hsmwVehicle.getImeiNum()) || StringUtils.isNotBlank(hsmwVehicle.getIdentifyingCode())) {
                    GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(hsmwVehicle.getImeiNum(),hsmwVehicle.getFlag(),hsmwVehicle.getIdentifyingCode());
                    if (StringUtils.isNotNull(entity) && StringUtils.isNotBlank(entity.getGpsLon())) {
                        vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
                    }
                }
                HashMap calculateParam = new HashMap();
                calculateParam.put("origin", vehicleLocalteInfo);
                calculateParam.put("destination", destinationLocateInfo);
                Long mapTimeAndDistance = GaoDeInfoUtils.calculateDistance(calculateParam);
                long distence = mapTimeAndDistance / 1000;
                List<com.hsmw.domain.vo.DriverCountVO> list = hsmwUserDriverService.findUserDriverListBYVehicleId(hsmwVehicle.getVehicleId());
                hsmwVehicle.setDriverCountVOS(list);
                hsmwVehicle.setDistance(String.valueOf(distence));
            }
        }
        System.out.println(System.currentTimeMillis() -start);

        if(StringUtils.isBlank(hsmwItem.getVehicleUnitId())){
            for (IdleVehicleVo idleVehicleVo : vehicleVoList) {
                long parseLong = Long.parseLong(idleVehicleVo.getDistance());
                if(parseLong > 100){
                    continue;
                }else {
                    idleVehicleVos.add(idleVehicleVo);
                }
            }
            return new DataResponse(SUCCESS,idleVehicleVos);
        }else {
            // 指定车辆单位id不为空 证明 工长所属项目有归属公司
            HsmwLeasingCompanyRule hsmwLeasingCompanyRule = hsmwLeasingCompanyRuleService.getOne(new LambdaQueryWrapper<HsmwLeasingCompanyRule>().eq(HsmwLeasingCompanyRule::getLeasingCompanyId, hsmwItem.getVehicleUnitId()));
            // 返回数据不为空 证明工长所在项目的归属公司设置了规则 且规则全部生效
            if (StringUtils.isNotNull(hsmwLeasingCompanyRule)) {
                // 混凝土标号 预计放量 与规则信息不一致
                long ruleMinExVolume = Long.parseLong(hsmwLeasingCompanyRule.getMinExpectVolume());
                long ruleMaxExVolume = Long.parseLong(hsmwLeasingCompanyRule.getMaxExpectVolume());
                long queryExVolume = Long.parseLong(queryFreeParams.getExpectVolume());
                long ruleDistance = Long.parseLong(hsmwLeasingCompanyRule.getKilometers());
                // 全部不满足规则条件 则显示100公里内 对应类型的车辆
                if (queryExVolume > ruleMaxExVolume || queryExVolume < ruleMinExVolume || !StringUtils.contains(queryFreeParams.getConcreteNumber(),hsmwLeasingCompanyRule.getConcreteNumber())) {
                    return new DataResponse(SUCCESS, vehicleVoList);
                }
                for (IdleVehicleVo idleVehicleVo : vehicleVoList) {
                    long parseLong = Long.parseLong(idleVehicleVo.getDistance());
                    if(parseLong > ruleDistance){
                        continue;
                    }else {
                        idleVehicleVos.add(idleVehicleVo);
                    }
                }
            }
            System.out.println(System.currentTimeMillis() -start);
            return new DataResponse(SUCCESS, idleVehicleVos);
        }

    }


    /**
     * 散户查询当前订单，已完成，已取消的订单 以及司机
     */
    @Log(title = "混天凝APP端查询当前订单，已完成，已取消的订单", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP端查询当前订单，已完成，已取消的订单", notes = "混天凝APP端查询当前订单，已完成，已取消的订单", produces = "application/json")
    @PostMapping("selectFindOrderStatusList")
    public DataResponse selectFindOrderStatusList(@RequestBody @Valid BasePage<HsmwOrder> basePage){
        String param = basePage.getQueryParam();
        IPage page = new Page(basePage.getPageNo(), basePage.getPageSize());
        HsmwHtnUser currentHtnHsmwUser =currentHsmwUserUtils.getCurrentHtnUserInfo();
        if(currentHtnHsmwUser == null){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"获取参数信息失败");
        }
        if(HtnUserTypeEnum.NORMAL.getValue().equals(currentHtnHsmwUser.getType())){
            return new DataResponse();
        }
        if(StringUtils.isBlank(param)){
            return new DataResponse(VALIDATE_FAILED,"查询的订单状态为空");
        }
        // 公司用户或者搅拌站用户
        if(StringUtils.isNotBlank(currentHtnHsmwUser.getType())
                && (HtnUserTypeEnum.CONCRETE.getValue().equals(currentHtnHsmwUser.getType())
                ||HtnUserTypeEnum.COMPANY.getValue().equals(currentHtnHsmwUser.getType()))){
            return new DataResponse(hsmwOrderService.selectOrderStatusList(page,param,currentHtnHsmwUser.getOwnCompanyId(),null,basePage.getItmeNameOrDriverName(),basePage.getStartTime(),basePage.getEndTime()));
        }else {
            //工长用户
            return new DataResponse(hsmwOrderService.selectOrderStatusList(page,param,null,currentHtnHsmwUser.getId(),basePage.getItmeNameOrDriverName(),basePage.getStartTime(),basePage.getEndTime()));
        }
    }


    /**
     * 混天凝APP端收藏司机
     */
    @Log(title = "混天凝APP端收藏司机", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP端收藏司机", notes = "混天凝APP端收藏司机", produces = "application/json")
    @PostMapping("vehicleCollect")
    public DataResponse vehicleCollect(String vehicleId){
        if(StringUtils.isBlank(vehicleId)){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"您输入的车辆ID为空");
        }
        try {
            HsmwHtnUser loginUser  =currentHsmwUserUtils.getCurrentHtnUserInfo();
            HsmwVehicle vehicle = hsmwVehicleService.getVehicleById(vehicleId);
            LambdaQueryWrapper<HsmwVehicleCollect> lambdaQueryWrapper = new LambdaQueryWrapper<HsmwVehicleCollect>()
                    .eq(HsmwVehicleCollect::getVehicleId,vehicleId);
            if(HtnUserTypeEnum.FOREMAN.getValue().equals(loginUser.getType())){
                lambdaQueryWrapper.eq(HsmwVehicleCollect::getUserId,loginUser.getId());
            }else {
                lambdaQueryWrapper.eq(HsmwVehicleCollect::getCompanyId,loginUser.getOwnCompanyId());
            }
            List<HsmwVehicleCollect> collects = hsmwVehicleCollectMapper.selectList(lambdaQueryWrapper);
            if(CollectionUtil.isNotEmpty(collects)){
                return new DataResponse(SUCCESS,"收藏成功");
            }
            HsmwVehicleCollect collect = new HsmwVehicleCollect();
            collect.setVehicleId(vehicleId);
            collect.setVehicleModel(vehicle.getVehicleModel());
            collect.setVehicleType(vehicle.getVehicleType());
            collect.setVehicleBrand(vehicle.getVehicleBrand());
            collect.setUserId(loginUser.getId());
            collect.setVehiclePlate(vehicle.getVehiclePlate());
            collect.setCarNum(vehicle.getCarNum());
            collect.setCompanyId(loginUser.getOwnCompanyId());
            hsmwVehicleCollectMapper.insert(collect);
            return new DataResponse(SUCCESS,"收藏成功");
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"收藏车辆灰失败，请联系管理员！");
        }
    }

    /**
     * 散户查询当前订单，已完成，已取消的订单 以及司机
     */
    @Log(title = "混天凝APP端取消收藏司机", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP端取消收藏司机", notes = "混天凝APP端取消收藏司机", produces = "application/json")
    @PostMapping("cancelVehicleCollect")
    public DataResponse cancelVehicleCollect(String vehicleId){
        if(StringUtils.isBlank(vehicleId)){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"您输入的车辆ID为空");
        }
        try {
            HsmwHtnUser loginUser  =currentHsmwUserUtils.getCurrentHtnUserInfo();
            LambdaQueryWrapper<HsmwVehicleCollect> lambdaQueryWrapper = new LambdaQueryWrapper<HsmwVehicleCollect>()
                    .eq(HsmwVehicleCollect::getVehicleId,vehicleId);
            if(HtnUserTypeEnum.FOREMAN.getValue().equals(loginUser.getType())){
                lambdaQueryWrapper.eq(HsmwVehicleCollect::getUserId,loginUser.getId());
            }else {
                lambdaQueryWrapper.eq(HsmwVehicleCollect::getCompanyId,loginUser.getOwnCompanyId());
            }
            hsmwVehicleCollectMapper.delete(lambdaQueryWrapper);
            return new DataResponse(SUCCESS,"取消收藏成功");
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"取消收藏成功失败，请联系管理员！");
        }
    }

    /**
     * 散户查询当前订单，已完成，已取消的订单 以及司机
     */
    @Log(title = "混天凝APP端查询当前订单详情", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP端查询当前订单详情", notes = "混天凝APP端查询当前订单详情", produces = "application/json")
    @PostMapping("getOrderDetailInfo")
    public DataResponse getOrderDetailInfo(String relationId){
        if(StringUtils.isBlank(relationId)){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"您输入的子订单ID为空");
        }
        HashMap param = new HashMap();
        param.put("relationId",relationId);
        return new DataResponse(hsmwOrderService.selectOrderDetailByRelationId(param));
    }



    /**
     * 混天凝app端查询个人信息
     */
    @Log(title = "混天凝app端查询个人信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝app端查询个人信息", notes = "混天凝app端查询个人信息", produces = "application/json")
    @PostMapping("findForceManInfoById")
    public DataResponse findForceManInfoById(){
        ForemanInformationVo foremanInformationVo = new ForemanInformationVo();
        HsmwHtnUser currentHtnHsmwUser =currentHsmwUserUtils.getCurrentHtnUserInfo();
        if(currentHtnHsmwUser != null){
            foremanInformationVo.setAvatar(currentHtnHsmwUser.getAvatar());
            foremanInformationVo.setUserPhone(currentHtnHsmwUser.getUsername());
            foremanInformationVo.setUserName(currentHtnHsmwUser.getName());
            foremanInformationVo.setForemanType(currentHtnHsmwUser.getForemanType());
            foremanInformationVo.setUserId(currentHtnHsmwUser.getId());
            foremanInformationVo.setType(currentHtnHsmwUser.getType());
            foremanInformationVo.setAuditStatus(currentHtnHsmwUser.getAuditStatus());
            foremanInformationVo.setRoleType(currentHtnHsmwUser.getRoleType());
            foremanInformationVo.setOwnCompanyId(currentHtnHsmwUser.getOwnCompanyId());
            foremanInformationVo.setOwnCompanyName(currentHtnHsmwUser.getOwnCompanyName());
            HsmwItem byId = hsmwItemService.getById(currentHtnHsmwUser.getItemId());
        }
        return new DataResponse(foremanInformationVo);
    }
    @Log(title = "工长查询订单详情", businessType = BusinessType.QUERY)
    @ApiOperation(value = "工长查询订单详情", notes = "工长查询订单详情", produces = "application/json")
    @ApiImplicitParam(name = "orderId",value = "订单id",dataType = "String")
    @PostMapping("findOrderDetailsByOrderId")
    public DataResponse findOrderDetailsByOrderId(String orderId){
        return new DataResponse(hsmwOrderService.findOrderDetailsByOrderId(orderId));
    }

    /**
     * 散户常用项目址查询
     *
     * @param
     * @return
     */
    @Log(title = "散户常用项目址查询", businessType = BusinessType.QUERY)
    @ApiOperation(value = "散户常用项目址查询： ", notes = "散户常用项目址查询", produces = "application/json")
    @PostMapping("/getRetailerRecentAdress")
    public DataResponse getRetailerRecentAdress() {
        try {
            LoginUser currentUser = currentHsmwUserUtils.getCurrentUserInfo();
            List<RetailerAdressInfoVO> addressInfo = hsmwOrderService.getRetailerRecentAdress(currentUser.getId());
            return  new DataResponse(addressInfo);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"散户常用项目址查询失败，请联系管理员！");
        }
    }

    @Log(title = "工长 确认方量", businessType = BusinessType.QUERY)
    @ApiOperation(value = "工长 确认方量 ", notes = "工长确认订单方量", produces = "application/json")
    @ApiImplicitParam(name = "orderId",value = "订单id",dataType = "String")
    @PostMapping("ensureOrderVolume")
    public DataResponse ensureOrderVolume(String orderId){
        HsmwOrder order = hsmwOrderService .getHsmwOrderById(orderId);
        order.setEnsureVolumeFlag(CommonConstants.YES);
        order.setEnsureTime(LocalDateTime.now());
        hsmwOrderService.updateById(order);

        HsmwConcreteOperateRecord record = new HsmwConcreteOperateRecord();
        LoginUser user = currentHsmwUserUtils.getCurrentUserInfo();
        record.setOrderId(orderId);
        record.setOperUsername(user.getUsername());
        record.setOperName(user.getName());
        record.setOperUser(user.getId());
        record.setOperType(OperTypeEnum.ENSURE.getValue());
        record.setUserType(UserTypeEnum.FOREMAN.getValue());
        record.setRemark("工长方量");
        hsmwConcreteOperateRecordService.save(record);

        return new DataResponse(hsmwOrderService.findOrderDetailsByOrderId(orderId));
    }

    @Log(title = "叫车端 修改用户信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "叫车端 修改用户信息", notes = "新增或修改user信息", produces = "application/json")
    @PostMapping("saveOrUpdateUser")
    public DataResponse saveOrUpdateUser(@RequestBody HsmwHtnUser hsmwUser){ if(StringUtils.isBlank(hsmwUser.getId())){
        return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您输入的工长id为空！");
    }
        if(StringUtils.isNotBlank(hsmwUser.getId())){
            List<HsmwHtnUser> list = hsmwHtnUserService.list();
            for (HsmwHtnUser user : list) {
                if(StringUtils.equals(user.getUsername(),hsmwUser.getUsername())){
                    System.err.println(hsmwUser.getUsername());
                    return new DataResponse<>(CommonConstants.ResponseStatus.FAIL,"手机号重复");
                }
            }
            hsmwHtnUserService.updateById(hsmwUser);
        }
        return new DataResponse(SUCCESS);
    }




    @Log(title = "工长注销账号", businessType = BusinessType.QUERY)
    @ApiOperation(value = "工长注销账号", notes = "工长注销账号", produces = "application/json")
    @ApiImplicitParam(name = "用户id",value = "id",dataType = "String")
    @PostMapping("deleteHsmwUserById")
    public DataResponse deleteHsmwUserById(String id){
        if(StringUtils.isBlank(id)){
            return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您输入的工长id为空！");
        }
        HsmwHtnUser user = hsmwHtnUserService.getById(id);
        //搅拌站负责人和泵送公司负责人注销时提示负责人不能注销
        if ((HtnUserTypeEnum.COMPANY.getValue().equals(user.getType()) || HtnUserTypeEnum.CONCRETE.getValue().equals(user.getType())) && HtnUserRoleEnum.LEADING.getValue().equals(user.getRoleType())){
            return  new DataResponse(CommonConstants.ResponseStatus.FZR,"负责人不能注销");
        }
        //1.调度或项目工长或项目负责人注销后，从员工管理和项目人员中直接删除
        if ((HtnUserTypeEnum.COMPANY.getValue().equals(user.getType()) || HtnUserTypeEnum.CONCRETE.getValue().equals(user.getType())) && HtnUserRoleEnum.DISPATCH.getValue().equals(user.getRoleType())){
            //如果是调度 那么 将 调度的 邀请记录删除掉
            hsmwInviteRecordService.remove(new LambdaQueryWrapper<HsmwInviteRecord>()
                    .eq(HsmwInviteRecord::getInviteeUserId,user.getId())
                    .eq(HsmwInviteRecord::getInviteStatus,InviteStatusEnum.RECEIVED.getValue())
                    .in(HsmwInviteRecord::getInviteType,InviteTypeEnum.CONCRETE_INVITE_DISPATCH.getValue(),InviteTypeEnum.COMPANY_INVITE_DISPATCH.getValue()));
        }
        if(HtnUserTypeEnum.FOREMAN.getValue().equals(user.getType())){
            //如果是工长用户  移除 项目和工长的关联关系表
            hsmwForcemanItemMapper.delete(new LambdaQueryWrapper<HsmwForcemanItem>()
                    .eq(HsmwForcemanItem::getForcemanId,user.getId()));
        }
        user.setEnabled(false);
        user.setRoleType(null);
        user.setOwnCompanyId(null);
        user.setOwnCompanyId(null);
        user.setType(null);
        user.setUsername("该混天凝账号已注销");
        hsmwHtnUserService.unregisterUser(user.getId());
        return new DataResponse(SUCCESS);
    }



    /**
     * 获取全部项目的信息
     *
     * @param
     * @return
     */
    @Log(title = "获取全部项目的信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "获取全部项目的信息", notes = "获取全部项目的信息", produces = "application/json")
    @PostMapping("/getHsmwItemList")
    public DataResponse getHsmwItemList(@RequestBody @Valid BasePage<HsmwItem> basePage) {
        IPage page = new Page(basePage.getPageNo(), basePage.getPageSize());
        IPage<HsmwItem>  items = new Page<>();
        HsmwHtnUser currentHtnHsmwUser =currentHsmwUserUtils.getCurrentHtnUserInfo();
        HsmwItem param =basePage.getRequestData();
        if(StringUtils.isNull(param)){
            param = new HsmwItem();
        }
        if(StringUtils.isNotBlank(basePage.getItemName())){
            param.setName(basePage.getItemName());
        }
        if(CollectionUtil.isNotEmpty(basePage.getConstructionUnitNames())){
            param.setConstructionUnitNames(basePage.getConstructionUnitNames());
        }
        if(HtnUserTypeEnum.COMPANY.getValue().equals(currentHtnHsmwUser.getType()) || HtnUserTypeEnum.CONCRETE.getValue().equals(currentHtnHsmwUser.getType())){
            param.setVehicleUnitId(currentHtnHsmwUser.getOwnCompanyId());
            items = hsmwItemService.selectItemInfoList(page,param);
        }
        if(HtnUserTypeEnum.FOREMAN.getValue().equals(currentHtnHsmwUser.getType())){
            items = hsmwItemService.selectItemInfoListByForemanId(page,currentHtnHsmwUser.getId());
        }
        if(StringUtils.isNotBlank(basePage.getCurrentLocate())){
            List<HsmwItem> records = items.getRecords();
            for(HsmwItem itemInfo :records){
                HashMap calculateParam = new HashMap();
                calculateParam.put("origin", basePage.getCurrentLocate());
                calculateParam.put("destination", itemInfo.getLng()+","+itemInfo.getLat());
                Long mapTimeAndDistance = GaoDeInfoUtils.calculateDistance(calculateParam);
                Long distence = mapTimeAndDistance / 1000;
                System.err.println("距离--->" + distence);
                itemInfo.setDistance(StringUtils.isNull(distence)? 0L:distence);
            }
            items.setRecords(records);
        }
        return DataResponse.success(items);
    }

    /**
     * 获取项目全部项目的信息
     *
     * @param
     * @return
     */
    @Log(title = "获取项目联系人信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "获取项目联系人信息", notes = "获取项目全部工长信息", produces = "application/json")
    @PostMapping("/getLinkListByItemId")
    public DataResponse getHsmwAuditPage(String itemId) {
        HashMap param = new HashMap();
        param.put("itemId",itemId);
        List<HsmwItemLinkman > apps =hsmwItemLinkmanMapper.selectLinkmanListByItemId(param);
        return DataResponse.success(apps);
    }

    /**
     * 获取项目全部项目的信息
     *
     * @param
     * @return
     */
    @Log(title = "获取项目纯 联系人信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "获取项目纯 联系人信息", notes = "获取项目纯 联系人信息", produces = "application/json")
    @PostMapping("/getLinkmanList")
    public DataResponse getLinkmanList(String itemId) {
        HashMap param = new HashMap();
        param.put("itemId",itemId);
        List<HsmwItemLinkman > apps =hsmwItemLinkmanMapper.selectLinkmanByItemId(param);
        return DataResponse.success(apps);
    }




    /**
     * 获取全部项目的信息
     *
     * @param
     * @return
     */
    @Log(title = "获取指定泵车订单的方量更新记录", businessType = BusinessType.QUERY)
    @ApiOperation(value = "获取指定泵车订单的方量更新记录", notes = "获取指定泵车订单的方量更新记录", produces = "application/json")
    @PostMapping("/getPumpOperList")
    public DataResponse getPumpOperList(String relationId) {
        List<HsmwVolumeRecord > recordes = hsmwVolumeRecordService.list(new LambdaQueryWrapper<HsmwVolumeRecord>()
                .eq(HsmwVolumeRecord::getRelationId,relationId));
        return DataResponse.success(recordes);
    }

    @Log(title = "重新派单后-工长下单", businessType = BusinessType.QUERY)
    @ApiOperation(value = "重新派单后-工长下单", notes = "重新派单后-工长下单", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "requestId",value = "需求表id",dataType = "String"),
            @ApiImplicitParam(name = "orderId",value = "订单id",dataType = "String"),
            @ApiImplicitParam(name = "vehicleId",value = "车辆id",dataType = "String"),
            @ApiImplicitParam(name = "time",value = "到达时间",dataType = "localDateTime")
    })
    @PostMapping("/overbookingOrder")
    public DataResponse overbookingOrder(String requestId,String time,String orderId,String vehicleId){

        if(StringUtils.isBlank(requestId)){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"传递参数错误");
        }
        HsmwOrderVehicleRequest request = hsmwOrderVehicleRequestService.getById(requestId);
        if(request == null){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"没有该需求信息，请检查！");
        }
        HsmwOrder order = hsmwOrderService.getById(orderId);
        BeanUtilsOrderVO beanUtilsOrderVO = new BeanUtilsOrderVO();
        BeanUtils.copyProperties(order,beanUtilsOrderVO);
        String newOrderId = CommonUtils.generateId(beanUtilsOrderVO);
        beanUtilsOrderVO.setId(newOrderId);
        beanUtilsOrderVO.setCreateTime(LocalDateTime.now());
        hsmwOrderService.saveOrderVo(beanUtilsOrderVO);

        HsmwConstructionPosition position = hsmwConstructionPositionService.getOne(new LambdaQueryWrapper<HsmwConstructionPosition>().eq(HsmwConstructionPosition::getOrderId, order.getId()));
        BeanUtilsPosition beanUtilsPosition = new BeanUtilsPosition();
        BeanUtils.copyProperties(position,beanUtilsPosition);
        beanUtilsPosition.setOrderId(beanUtilsOrderVO.getId());
        beanUtilsPosition.setId(CommonUtils.generateId(beanUtilsPosition));
        hsmwConstructionPositionService.saveBeanPositionVo(beanUtilsPosition);

        BeanUtilsRequestVO beanUtilsRequestVO = new BeanUtilsRequestVO();
        BeanUtils.copyProperties(request,beanUtilsRequestVO);
        beanUtilsRequestVO.setId(CommonUtils.generateId(beanUtilsRequestVO));
        beanUtilsRequestVO.setRequestStatus(null);
        beanUtilsRequestVO.setOrderId(beanUtilsOrderVO.getId());
        beanUtilsRequestVO.setCreateUser(beanUtilsOrderVO.getCreateUser());
        beanUtilsRequestVO.setReachTime(LocalDateTime.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));

        hsmwOrderVehicleRequestMapper.saveRequestInfo(beanUtilsRequestVO);
        System.err.println("新需求id"+beanUtilsRequestVO.getId());
        placeAnOrderUtils.placeAnOrder(beanUtilsRequestVO.getId());
        HsmwOrderVehicleRequest vehicleRequest = hsmwOrderVehicleRequestService.getById(beanUtilsRequestVO.getId());
        if(vehicleRequest != null){
            if(StringUtils.isBlank(vehicleRequest.getRequestStatus()) || !StringUtils.equals("2",vehicleRequest.getRequestStatus())){
                vehicleRequest.setRequestStatus(RequestStatusEnum.UNRECEIVED.getValue());
            }
        }
        hsmwOrderVehicleRequestService.updateById(vehicleRequest);

        HsmwPumpOperateRecord record = new HsmwPumpOperateRecord();
        HsmwOrder hsmwOrder = hsmwOrderService.getHsmwOrderById(orderId);
        if(StringUtils.equals(hsmwOrder.getLinkmanType(),"0") || StringUtils.equals(hsmwOrder.getLinkmanType(),"1")){
            HsmwHtnUser hsmwHtnUser = hsmwHtnUserService.getById(hsmwOrder.getLinkmanId());
            record.setName(hsmwHtnUser.getName());
            record.setUsername(hsmwHtnUser.getUsername());
        }else {
            HsmwItemLinkman hsmwItemLinkman = hsmwItemLinkmanMapper.selectById(hsmwOrder.getLinkmanId());
            record.setName(hsmwItemLinkman.getName());
            record.setUsername(hsmwItemLinkman.getPhoneNum());
        }
        record.setOrderId(newOrderId);
        record.setUserType("工长");
        record.setOrderStatus(PumpOrderStatusEnum.UNRECEIVED.getValue());
        record.setOperContent("下单成功");
        hsmwPumpOperateRecordService.save(record);

        return new DataResponse(SUCCESS);
    }


    @ApiOperation(value = "重新派单后-工长取消下单", notes = "重新派单后-工长取消下单", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pushId",value = "推送信息表id",dataType = "String")
    })
    @PostMapping("/cancelOrderByForeMan")
    public DataResponse cancelOrderByForeMan(String pushId){

        if( StringUtils.isBlank(pushId) ){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"传递参数错误");
        }

        HsmwPushInfo pushInfo = hsmwPushInfoService.getById(pushId);
        pushInfo.setStatus("1");
        boolean pushSuc = hsmwPushInfoService.updateById(pushInfo);
        if(pushSuc){
            return new DataResponse(SUCCESS,"取消成功");
        }

        return new DataResponse(CommonConstants.ResponseStatus.FAIL,"取消失败");
    }


    @Log(title = "重新派单后-获取推送消息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "重新派单后-获取推送消息", notes = "重新派单后-获取推送消息", produces = "application/json")
    @PostMapping("/obtainInfoByForeManId")
    public DataResponse obtainInfoByForeManId(){
        LoginUser user = currentHsmwUserUtils.getCurrentUserInfo();
        Map map = new HashMap();
        if(user == null){
            return new DataResponse(CommonConstants.ResponseStatus.UNAUTHORIZED,"登录信息错误");
        }
        List<HsmwPushInfo> list = hsmwPushInfoService.list(new LambdaQueryWrapper<HsmwPushInfo>()
                .eq(HsmwPushInfo::getForemanId, user.getId())
                .eq(HsmwPushInfo::getStatus,"0"));
        List<HsmwDriverNews> news = hsmwDriverNewsService.list(new LambdaQueryWrapper<HsmwDriverNews>().eq(HsmwDriverNews::getUserId, user.getId()).eq(HsmwDriverNews::getAlreadyRead,"0"));
        if(CollectionUtil.isNotEmpty(news)){
            map.put("alreadyRead",1);
        }else {
            map.put("alreadyRead",0);
        }
        map.put("list",list);
        return new DataResponse(map);
    }



    /**
     * 查询我的系统消息
     *
     * @param
     * @return
     */
    @Log(title = "工长端 查询我的系统消息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "工长端 查询我的系统消息", notes = "查询我的系统消息", produces = "application/json")
    @PostMapping("/getSystemMsg")
    public DataResponse getSystemMsg(@RequestBody BasePage<HsmwDriverNews> basePage) {
        try {
            IPage page = new Page(basePage.getPageNo(), basePage.getPageSize());
            HsmwDriverNews hsmwRole = basePage.getRequestData();
            Assert.notNull(page.getCurrent(), "页码不能为空");
            Assert.notNull(page.getSize(), "页码不能为空");
            IPage<HsmwDriverNews> data = hsmwDriverNewsService.getHsmwNewsPage(page, hsmwRole);
            return new DataResponse(data);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"查询我的系统消息，请联系管理员！");
        }
    }

    /**
     * 将系统信息更新为已读
     *
     * @param
     * @return
     */
    @Log(title = "工长端 将系统信息更新为已读", businessType = BusinessType.QUERY)
    @ApiOperation(value = "工长端 将系统信息更新为已读", notes = "将系统信息更新为已读", produces = "application/json")
    @PostMapping("/updateAlreadyRead")
    public DataResponse updateAlreadyRead() {
        try {
            LoginUser loginUser = currentHsmwUserUtils.getCurrentUserInfo();
            HashMap param = new HashMap();
            param.put("userId",loginUser.getId());
            hsmwDriverNewsService.updateAlreadyRead(param);
            return new DataResponse();
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"将系统信息更新为已读，请联系管理员！");
        }
    }


    /**
     * 查询我的系统消息
     *
     * @param
     * @return
     */
    @Log(title = "查询我的未读的系统消息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查询我的未读的系统消息", notes = "查询我的未读的系统消息", produces = "application/json")
    @PostMapping("/getUnreadMsgCount")
    public DataResponse getUnreadMsgCount() {
        try {
            LoginUser user = currentHsmwUserUtils.getCurrentUserInfo();
            List<HsmwDriverNews> data = hsmwDriverNewsService.list(new LambdaQueryWrapper<HsmwDriverNews>()
                    .eq(HsmwDriverNews::getUserId,user.getId())
                    .eq(HsmwDriverNews::getAlreadyRead,CommonConstants.NO));
            HashMap res = new HashMap();
            res.put("unReadCount",CollectionUtil.isNotEmpty(data)?data.size():0);
            return new DataResponse(res);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"查询我的未读的系统消息，请联系管理员！");
        }
    }



    /**
     * 项目信息新增
     *
     * @param
     * @return
     */
    @Log(title = "自营或 平台账号创建订单的时候 新建项目", businessType = BusinessType.INSERT)
    @ApiOperation(value = "自营或 平台账号常见订单的时候 新增项目", notes = "中控项目信息新增", produces = "application/json")
    @PostMapping("/saveOrUpdateItemInfo")
    public DataResponse saveOrUpdateItemInfo(@RequestBody  ItemInfoVO  itemInfoVO) {
        try {
            HsmwHtnUser currentuser = currentHsmwUserUtils.getCurrentHtnUserInfo();
            HashMap result = new HashMap();
            if(StringUtils.isNotBlank(itemInfoVO.getItemId())){
                HashMap param = new HashMap();
                param.put("itemId",itemInfoVO.getItemId());
                boolean ifHasOrder =hsmwItemService.checkIfHasOrder(param);
                if(ifHasOrder){
                    return new DataResponse(CommonConstants.ResponseStatus.HAS_GOING_ORDER_UPDATE,null);
                }

                List<HsmwItem> items = hsmwItemService.list(new LambdaQueryWrapper<HsmwItem>()
                        .eq(HsmwItem::getName,itemInfoVO.getName())
                        .ne(HsmwItem::getId,itemInfoVO.getItemId())
                        .eq(HsmwItem::getVehicleUnitId,currentuser.getOwnCompanyId()));
                if(CollectionUtil.isNotEmpty(items)){
                    return  DataResponse.failure(ErrorCodeUtil.E_220,"您输入的项目名称已存在，请重新输入！");
                }
                HsmwItem hsmwItem = new HsmwItem();
                String identifyNum = CommonUtils.generateItemIdentifyNum();
                hsmwItem.setItemIdentifyNum(identifyNum);
                hsmwItem.setAuditStatus("2");
                hsmwItem.setUserPhone("0");
                hsmwItem.setName(itemInfoVO.getName());
                hsmwItem.setPositionDetail(itemInfoVO.getPositionDetail());
                hsmwItem.setConstructionUnitName(itemInfoVO.getConstructionUnitName());
                hsmwItem.setId(itemInfoVO.getItemId());
                hsmwItem.setLat(itemInfoVO.getLat());
                hsmwItem.setLng(itemInfoVO.getLng());
                hsmwItemService.updateById(hsmwItem);
                result.put("itemIdentifyNum",identifyNum);
                result.put("itemId",itemInfoVO.getItemId());
            } else {
                List<HsmwItem> items = hsmwItemService.list(new LambdaQueryWrapper<HsmwItem>()
                        .eq(HsmwItem::getName,itemInfoVO.getName())
                        .eq(HsmwItem::getVehicleUnitId,currentuser.getOwnCompanyId())
                        );
                if(CollectionUtil.isNotEmpty(items)){
                    return  DataResponse.failure(ErrorCodeUtil.E_220,"您输入的项目名称已存在，请重新输入！");
                }
                List<HsmwItemLinkman> users = hsmwItemLinkmanMapper.selectList(new LambdaQueryWrapper<HsmwItemLinkman>()
                        .eq(HsmwItemLinkman::getItemId,itemInfoVO.getItemId())
                        .eq(HsmwItemLinkman::getPhoneNum,itemInfoVO.getLinkmanUserPhone()));
                if(CollectionUtil.isNotEmpty(users)){
                    return new DataResponse(CommonConstants.ResponseStatus.FAIL,"您输入的联系人手机号重复，请重新输入！");
                }
                HsmwItem hsmwItem = new HsmwItem();
                String identifyNum = CommonUtils.generateItemIdentifyNum();
                hsmwItem.setItemIdentifyNum(identifyNum);
                hsmwItem.setAuditStatus("2");
                hsmwItem.setUserPhone("0");
                hsmwItem.setCreateUser(currentuser.getId());
                hsmwItem.setName(itemInfoVO.getName());
                hsmwItem.setPositionDetail(itemInfoVO.getPositionDetail());
                hsmwItem.setConstructionUnitName(itemInfoVO.getConstructionUnitName());
                //判断 创建项目的时候 是否传了 指定公司ID 如果没有传则 查询 当前自营账号绑定的租赁公司ID
                if( UserTypeEnum.CONCRETE.getValue().equals(currentuser.getType()) ){
                    HsmwConcretePlantInfo company = hsmwConcretePlantInfoMapper.selectById(currentuser.getOwnCompanyId());
                    if(StringUtils.isNotNull(company)){
                        hsmwItem.setVehicleUnitName(company.getPlantName());
                        hsmwItem.setVehicleUnitId(company.getId());
                    }
                }else {
                    HsmwLeasingCompany company = hsmwLeasingCompanyService.getById(currentuser.getOwnCompanyId());
                    if(StringUtils.isNotNull(company)){
                        hsmwItem.setVehicleUnitId(company.getId());
                        hsmwItem.setVehicleUnitName(company.getName());
                    }
                }
                hsmwItem.setLat(itemInfoVO.getLat());
                hsmwItem.setLng(itemInfoVO.getLng());
                String itemId =CommonUtils.generateId(hsmwItem);
                hsmwItem.setId(itemId);
                hsmwItem.setConstructionUnitName(itemInfoVO.getConstructionUnitName());
                hsmwItemService.save(hsmwItem);
                HsmwItemLinkman hsmwItemLinkman = new HsmwItemLinkman();
                hsmwItemLinkman.setItemId(itemId);
                hsmwItemLinkman.setItemName(itemInfoVO.getName());
                hsmwItemLinkman.setPhoneNum(itemInfoVO.getLinkmanUserPhone());
                hsmwItemLinkman.setName(itemInfoVO.getLinkmanName());
                String linkmanId = CommonUtils.generateId(hsmwItemLinkman);
                hsmwItemLinkman.setId(linkmanId);
                hsmwItemLinkmanMapper.insert(hsmwItemLinkman);
                result.put("itemIdentifyNum",identifyNum);
                result.put("itemId",itemId);
                result.put("linkmanId",linkmanId);
                HsmwItemLinkmanRelation rela = new HsmwItemLinkmanRelation();
                rela.setItemId(itemId);
                rela.setLinkmanId(linkmanId);
                hsmwItemLinkmanRelationMapper.insert(rela);
                // 根据选择的搅拌站IDS 进行 邀请 搅拌站
                String plantIds = itemInfoVO.getPlantIds();
                if(StringUtils.isNotBlank(plantIds)){
                    //如果 当前用户的类型是搅拌站 那么 当前用户所在的搅拌站 是默认选中的  并且不需要邀请 直接通过 生产邀请记录  生成 项目和搅拌站的关联关系
                   if(HtnUserTypeEnum.CONCRETE.getValue().equals(currentuser.getType()) && plantIds.contains(currentuser.getOwnCompanyId())){
                       HsmwItemConcreteRelation relation = new HsmwItemConcreteRelation();
                       relation.setConcreteId(currentuser.getOwnCompanyId());
                       relation.setConcreteName(currentuser.getOwnCompanyName());
                       relation.setItemId(itemId);
                       relation.setItemName(itemInfoVO.getName());
                       hsmwItemConcreteRelationService.save(relation);
                       //创建一条邀请成功的项目邀请搅拌站的邀请记录
                       HsmwInviteRecord record = new HsmwInviteRecord();
                       record.setItemId(itemId);
                       record.setItemName(itemInfoVO.getName());
                       record.setPlantId(currentuser.getOwnCompanyId());
                       record.setPlantName(currentuser.getOwnCompanyName());
                       record.setInviteUserId(currentuser.getId());
                       record.setInviteUserName(currentuser.getName());
                       record.setInviteUserTel(currentuser.getUsername());
                       record.setInviteType(InviteTypeEnum.ITEM_INVITE_CONCRETE.getValue());
                       record.setInviteStatus(InviteStatusEnum.RECEIVED.getValue());
                       hsmwInviteRecordService.save(record);
                       plantIds = plantIds.replace(currentuser.getOwnCompanyId(),"");
                   }
                   List<String> plantIdList = new ArrayList<>();
                   if(StringUtils.isNotBlank(plantIds)){
                       for(String str :plantIds.split(",")){
                           if(StringUtils.isNotBlank(str)){
                               plantIdList.add(str);
                           }
                       }
                   }
                   HsmwInviteRecord record = new HsmwInviteRecord();
                   record.setPlantIds(plantIdList);
                   record.setInviteType(InviteTypeEnum.ITEM_INVITE_CONCRETE.getValue());
                   record.setItemId(itemId);
                   record.setItemName(itemInfoVO.getName());
                   hsmwInviteRecordService.saveOrUpdateInviteInfo(record);
                }
            }
            return new DataResponse(SUCCESS,result);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"项目信息新增失败，请联系管理员！");
        }
    }



    /**
     * 项目信息新增
     *
     * @param
     * @return
     */
    @Log(title = "混天凝账号 创建订单的时候  删除项目", businessType = BusinessType.INSERT)
    @ApiOperation(value = "混天凝账号  创建订单的时候 删除项目", notes = "中控项目信息删除", produces = "application/json")
    @PostMapping("/removeItemInfo")
    public DataResponse removeItemInfo(@RequestBody  ItemInfoVO  itemInfoVO) {
        try {
            HsmwHtnUser currentUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
            HashMap result = new HashMap();
            if(StringUtils.isBlank(itemInfoVO.getItemId())){
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您输入的项目ID为空，请重新输入！");
            } else {
                HashMap param = new HashMap();
                param.put("itemId",itemInfoVO.getItemId());
                param.put("userId",currentUser.getId());
                boolean ifHasOrder =hsmwItemService.checkIfHasOrder(param);
                if(ifHasOrder){
                    return new DataResponse(CommonConstants.ResponseStatus.HAS_GOING_ORDER,"");
                }
                hsmwItemService.removeItemInfoById(itemInfoVO.getItemId());
                hsmwItemLinkmanMapper.delete(new LambdaQueryWrapper<HsmwItemLinkman>()
                        .eq(HsmwItemLinkman::getItemId,itemInfoVO.getItemId()));
                //删除 项目和工长的关联关系 表信息
                List<HsmwForcemanItem> forcemanItems = hsmwForcemanItemMapper.selectList(new LambdaQueryWrapper<HsmwForcemanItem>()
                        .eq(HsmwForcemanItem::getItemId,itemInfoVO.getItemId()));
                if (CollectionUtil.isNotEmpty(forcemanItems)){
                    for (HsmwForcemanItem forcemanItem : forcemanItems){
                        //首先判断一下 是否 该项目是不是 该工长的最后一个项目
                        List<HsmwForcemanItem> items = hsmwForcemanItemMapper.selectList(new LambdaQueryWrapper<HsmwForcemanItem>()
                                .eq(HsmwForcemanItem::getForcemanId, forcemanItem.getForcemanId())
                                .ne(HsmwForcemanItem::getItemId, forcemanItem.getItemId()));
                        if (CollectionUtil.isEmpty(items)) {
                            HashMap params= new HashMap();
                            params.put("userId", forcemanItem.getForcemanId());
                            hsmwHtnUserService.removeStuff(params);
                            HsmwHtnUser htnUser = hsmwHtnUserService.getHsmwUserById(forcemanItem.getForcemanId());
                            String  message = "您已经被项目移除，现在已经是普通用户！";
                            WebSocketReturnVO webSocketReturnVO = new WebSocketReturnVO();
                            webSocketReturnVO.setData(message);
                            webSocketReturnVO.setType("0");
                            TencentPushUtils.htnPushInviteMsg(message,htnUser.getUsername(),new WebSocketReturnVO());

                            //存储系统消息
                            HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
                            hsmwDriverNews.setUserId(htnUser.getId());
                            hsmwDriverNews.setMessage(message);
                            hsmwDriverNews.setAlreadyRead("0");
                            hsmwDriverNewsService.save(hsmwDriverNews);

                            //删除登录信息
                            redisTemplate.delete(forcemanItem.getForcemanId());
                        }
                        hsmwForcemanItemMapper.deleteById(forcemanItem.getId());
                    }
                }
            }
            return new DataResponse(result);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"项目信息删除失败，请联系管理员！");
        }
    }





    /**
     * 自营或 平台账号创建工长
     *
     * @param
     * @return
     */
    @Log(title = "混天凝APP创建或修改项目联系人", businessType = BusinessType.INSERT)
    @ApiOperation(value = "混天凝APP创建或修改项目联系人", notes = "混天凝APP创建或修改项目联系人", produces = "application/json")
    @PostMapping("/saveOrUpdateItemLinkman")
    public DataResponse saveOrUpdateItemLinkman(@RequestBody  HsmwItemLinkman  hsmwItemLinkman) {
        try {
            HashMap result = new HashMap();
            HashMap param = new HashMap();
            param.put("itemId",hsmwItemLinkman.getItemId());
            param.put("linkmanName",hsmwItemLinkman.getName());
            param.put("phoneNum",hsmwItemLinkman.getPhoneNum());
            if(StringUtils.isNotBlank(hsmwItemLinkman.getId())){
                param.put("linkmanId",hsmwItemLinkman.getId());
                boolean ifHasOrder =hsmwItemService.checkIfHasOrder(param);
                if(ifHasOrder){
                    return new DataResponse(CommonConstants.ResponseStatus.HAS_GOING_ORDER_UPDATE,null);
                }
                param.put("linkmanId",hsmwItemLinkman.getId());
                List<HsmwItemLinkman> users = hsmwItemLinkmanMapper.checkIfLinkmanExists(param);
                if(CollectionUtil.isNotEmpty(users)){
                    return new DataResponse(CommonConstants.ResponseStatus.REPETE_NUM_OR_NAME,null);
                }
                hsmwItemLinkmanMapper.updateById(hsmwItemLinkman);
                result.put("linkmanId",hsmwItemLinkman.getId());
            }else {
                List<HsmwItemLinkman> users = hsmwItemLinkmanMapper.checkIfLinkmanExists(param);
                if(CollectionUtil.isNotEmpty(users)){
                    return new DataResponse(CommonConstants.ResponseStatus.REPETE_NUM_OR_NAME,null);
                }
                String linkmanId = CommonUtils.generateId(hsmwItemLinkman);
                hsmwItemLinkman.setId(linkmanId);
                hsmwItemLinkmanMapper.insert(hsmwItemLinkman);
                HsmwItemLinkmanRelation relation = new HsmwItemLinkmanRelation();
                relation.setLinkmanId(linkmanId);
                relation.setItemId(hsmwItemLinkman.getItemId());
                hsmwItemLinkmanRelationMapper.insert(relation);
                result.put("linkmanId",linkmanId);
            }
            return new DataResponse(result);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"混天凝APP创建或修改项目联系人长失败，请联系管理员！");
        }
    }


    /**
     * 自营或 平台账号创建工长
     *
     * @param
     * @return
     */
    @Log(title = "混天凝APP删除项目联系人", businessType = BusinessType.INSERT)
    @ApiOperation(value = "混天凝APP删除项目联系人", notes = "混天凝APP删除项目联系人", produces = "application/json")
    @PostMapping("/removeItemLinkman")
    public DataResponse removeItemLinkman(@RequestBody  HsmwItemLinkman  hsmwItemLinkman) {
        try {
            HashMap param = new HashMap();
            param.put("linkmanId",hsmwItemLinkman.getId());
            boolean ifHasOrder =hsmwItemService.checkIfHasOrder(param);
            if(ifHasOrder){
                return new DataResponse(CommonConstants.ResponseStatus.HAS_GOING_ORDER,null);
            }
            //删除该联系人
            hsmwItemLinkmanMapper.deleteById(hsmwItemLinkman.getId());
            //删除该联系人与项目的关联关系
            hsmwItemLinkmanRelationMapper.delete(new LambdaQueryWrapper<HsmwItemLinkmanRelation>()
                    .eq(HsmwItemLinkmanRelation::getItemId,hsmwItemLinkman.getItemId())
                    .eq(HsmwItemLinkmanRelation::getLinkmanId,hsmwItemLinkman.getId()));
            return new DataResponse();
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"混天凝APP删除项目联系人失败，请联系管理员！");
        }
    }


    /**
     * 平台账号查询租赁公司列表
     *
     * @param
     * @return
     */
    @Log(title = "自营或 平台账号查询租赁公司列表", businessType = BusinessType.INSERT)
    @ApiOperation(value = "自营或 平台账号查询租赁公司列表", notes = "平台账号查询租赁公司列表", produces = "application/json")
    @PostMapping("/getCompanyList")
    public DataResponse getCompanyList() {
        try {
            List<HsmwLeasingCompany> companies = hsmwLeasingCompanyService.list(new LambdaQueryWrapper<HsmwLeasingCompany>()
                    .orderByDesc(HsmwLeasingCompany::getCreateTime));
            return new DataResponse(companies);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"自营或平台账号查询租赁公司列表失败，请联系管理员！");
        }
    }


    /**
     * 工长是否同意司机申请修改预计到达时间
     */
    @ApiOperation(value = "工长是否同意司机申请修改预计到达时间", notes = "工长是否同意司机申请修改预计到达时间", produces = "application/json")
    @PostMapping("/agreeDriverUpdateReachTime")
    public DataResponse agreeDriverUpdateReachTime(@RequestBody HsmwPushInfo hsmwPushInfo){

        return hsmwUserDriverService.agreeDriverUpdateReachTime(hsmwPushInfo);
    }


    @ApiOperation(value = "工长查看司机修改预计到达时间的申请", notes = "工长查看司机修改预计到达时间的申请", produces = "application/json")
    @ApiImplicitParam(name = "orderId",value = "订单id", dataType = "String")
    @PostMapping("/findDriverPushInfoByOrderId")
    public DataResponse findDriverPushInfoByOrderId(String relationId){
        if(StringUtils.isBlank(relationId)){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"传递参数不可为空");
        }
        return hsmwUserDriverService.findDriverPushInfoByOrderId(relationId);
    }

    @ApiOperation(value = "工长查看司机上报信息的申请", notes = "工长查看司机上报信息的申请", produces = "application/json")
    @ApiImplicitParam(name = "orderId",value = "订单id", dataType = "String")
    @PostMapping("/findDriverReportPushInfoByOrderId")
    public DataResponse findDriverReportPushInfoByOrderId(String relationId){
        if(StringUtils.isBlank(relationId)){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"传递参数不可为空");
        }
        return hsmwUserDriverService.findDriverReportPushInfoByOrderId(relationId);
    }


    @ApiOperation(value = "工长是否取消订单", notes = "工长是否取消订单", produces = "application/json")
    @PostMapping("/updateReportAndOrderInfo")
    public DataResponse updateReportAndOrderInfo(@RequestBody HsmwPushInfo hsmwPushInfo){
        if(StringUtils.isNull(hsmwPushInfo)){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"传递参数不可为空");
        }
        return hsmwUserDriverService.updateReportAndOrderInfo(hsmwPushInfo);
    }


    @Log(title = "查询所有的员工", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查询所有的员工", notes = "查询所有的员工", produces = "application/json")
    @PostMapping("/queryAllStuffs")
    public DataResponse queryAllStuffs(){
        HsmwHtnUser currentHtnUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
        List<HsmwHtnUser> stuffs = hsmwHtnUserService.list(new LambdaQueryWrapper<HsmwHtnUser>()
                .eq(HsmwHtnUser::getOwnCompanyId,currentHtnUser.getOwnCompanyId())
                .eq(HsmwHtnUser::getType,HtnUserTypeEnum.COMPANY.getValue()));
        return new DataResponse(stuffs);
    }


    @Log(title = "查询我的统计信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查询我的统计信息", notes = "查询我的统计信息", produces = "application/json")
    @PostMapping("/queryMyStatistics")
    public DataResponse queryMyStatistics(){
        HsmwHtnUser currentHtnUser = currentHsmwUserUtils.getCurrentHtnUserInfo() ;
        MyTotalInfoVO myTotalInfoVO = new MyTotalInfoVO();
        HashMap param = new HashMap();
        param.put("userId",currentHtnUser.getId());
        param.put("companyId",currentHtnUser.getOwnCompanyId());
        if(HtnUserTypeEnum.FOREMAN.getValue().equals(currentHtnUser.getType())){
            myTotalInfoVO = hsmwHtnUserService.getForemantotalInfo(param);
        }else {
            myTotalInfoVO = hsmwHtnUserService.getMytotalInfo(param);
        }
        return new DataResponse(myTotalInfoVO);
    }


    @Log(title = "泵送设置信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "泵送设置信息", notes = "泵送设置信息", produces = "application/json")
    @PostMapping("/pumpSetupInfo")
    public DataResponse pumpSetupInfo(){
        return  hsmwHtnUserService.pumpSetupInfo();
    }


    @Log(title = "泵送设置查询可以选择的租赁公司", businessType = BusinessType.QUERY)
    @ApiOperation(value = "泵送设置查询可以选择的租赁公司 2 . 租赁公司查询可用合作公司 3.搅拌站查询自营公司 4. 搅拌站查询合作公司", notes = "泵送设置查询可以选择的租赁公司", produces = "application/json")
    @ApiImplicitParam(name = "type",value = "查询租赁公司列表的类型  ", dataType = "String")
    @PostMapping("/getAvaliableCompany")
    public DataResponse getAvaliableCompany(String type){
        return  hsmwHtnUserService.getAvaliableCompany(type);
    }


    @Log(title = "租赁公司查询车辆列表", businessType = BusinessType.QUERY)
    @ApiOperation(value = "租赁公司查询车辆列表 ", notes = "租赁公司查询车辆列表", produces = "application/json")
    @PostMapping("/getVehicleList")
    public DataResponse getVehicleList(@RequestBody @Valid BasePage<HsmwVehicle> basePage) {
        try {
            IPage page = new Page(basePage.getPageNo(), basePage.getPageSize());
            HsmwVehicle hsmwVehicle = basePage.getRequestData();
            if (StringUtils.isNull(hsmwVehicle)) {
                hsmwVehicle = new HsmwVehicle();
            }
            HsmwHtnUser currentUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
            hsmwVehicle.setLeasingCompanyId(currentUser.getOwnCompanyId());
            IPage<HsmwVehicle> data = hsmwVehicleService.getVehiclePage(page, hsmwVehicle);
            List<HsmwVehicle> vehicles = data.getRecords();
            for (HsmwVehicle vehicle : vehicles) {
                HashMap param = new HashMap();
                param.put("vehicleId", vehicle.getId());
                List<DriverInfoVO> driverCountVOS = hsmwOrderMapper.findDriverListByehicleId(param);
                vehicle.setDriverCountVOS(driverCountVOS);
                if(StringUtils.isNotBlank(vehicle.getImeiNum()) || StringUtils.isNotBlank(vehicle.getIdentifyingCode())){
                    GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(vehicle.getImeiNum(),vehicle.getFlag(),vehicle.getIdentifyingCode());
                    if(StringUtils.isNotNull(entity) && StringUtils.isNotBlank(entity.getGpsLon())){
                        vehicle.setLocation(entity.getGpsLon()+","+entity.getGpsLat());
                        vehicle.setDirect(entity.getDirect());
                    }else {
                        vehicle.setLocation(vehicle.getMobileLocate());
                        vehicle.setDirect(vehicle.getMobileDirect());
                    }
                }else {
                    vehicle.setLocation(vehicle.getMobileLocate());
                    vehicle.setDirect(vehicle.getMobileDirect());
                }
            }
            data.setRecords(vehicles);
            return new DataResponse(SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }

    @Log(title = "混天凝APP 司机下车", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 司机下车 传司机ID ", notes = "司机下车", produces = "application/json")
    @ApiImplicitParam(value = "司机id", name = "id", dataType = "String")
    @PostMapping("driverTakeOffice")
    public DataResponse driverTakeOffice(String id){
        try {
            HsmwUserDriver hsmwUserDriver = hsmwUserDriverService.getById(id);
            String vehicleId = hsmwUserDriver.getVehicleId();
            if (CommonConstants.DRIVER_WORK.equals(hsmwUserDriver.getWorkStatus())){
                HashMap param = new HashMap();
                param.put("vehicleId",vehicleId);
                List<CurrentOrderInfoVO> orderList = hsmwOrderVehicleRelationService.getGoingOrderListByParam(param);
                if(CollectionUtil.isNotEmpty(orderList)){
                    //有进行中订单
                    List<HsmwUserDriver> userDrivers = hsmwUserDriverService.list(new LambdaQueryWrapper<HsmwUserDriver>()
                            .eq(HsmwUserDriver::getVehicleId, vehicleId)
                            .eq(HsmwUserDriver::getWorkStatus,CommonConstants.DRIVER_WORK));
                    if(CollectionUtil.isNotEmpty(userDrivers) && userDrivers.size() == 1){
                        return new DataResponse(CommonConstants.ResponseStatus.ONLY_ONE_DRIVER,null);
                    }else {
                        hsmwUserDriver.setVehicleId(null);
                        hsmwUserDriver.setWorkStatus(CommonConstants.CHANGING_CARS);
                    }
                }else {
                    //没有进行中订单
                    hsmwUserDriver.setVehicleId(null);
                    hsmwUserDriver.setWorkStatus(CommonConstants.CHANGING_CARS);
                }
            }else {
                //司机状态不是工作中 直接换成 换车中
                hsmwUserDriver.setVehicleId(null);
                hsmwUserDriver.setWorkStatus(CommonConstants.CHANGING_CARS);
            }
            HsmwVehicle vehicle = hsmwVehicleService.getVehicleById(vehicleId);
            HsmwHtnUser  currentUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
            HsmwDriverUser driverUser = hsmwDriverUserService.getById(hsmwUserDriver.getUserId());
            String[] params = new String[]{currentUser.getName(),vehicle.getVehiclePlate()};
            SendSmsUtil.sendSmsWithParam(appId, appKey, params, driverRemoveVehicle, smsSign, driverUser.getUsername());
            String msg = "您已被"+currentUser.getName()+"从"+vehicle.getVehiclePlate()+"中移出，目前处于没车状态";
            TencentPushUtils.pushMsg(msg,driverUser.getUsername(),"");
            hsmwUserDriverService.updateById(hsmwUserDriver);

            HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
            hsmwDriverNews.setUserId(driverUser.getId());
            hsmwDriverNews.setMessage(msg);
            hsmwDriverNews.setAlreadyRead("0");
            hsmwDriverNewsService.save(hsmwDriverNews);

            HashMap res = new HashMap();
            res.put("id",id);
            return new DataResponse(SUCCESS,res);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }

    }


    @Log(title = "混天凝APP 司机改变状态", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 司机改变状态", notes = "司机改变状态", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "司机id", name = "id", dataType = "String"),
            @ApiImplicitParam(value = "工作状态 切换为 '接单中'或者 '休息中'  ", name = "workStatus", dataType = "String")
    })
    @PostMapping("updateDriverWorkStatus")
    public DataResponse updateDriverWorkStatus(String id,String  workStatus){
        try {
            /*if(CommonConstants.DRIVER_ACCEPT_ORDER.equals(workStatus)){
                List<HsmwDriverClass> list = hsmwDriverClassService.list(new LambdaQueryWrapper<HsmwDriverClass>().eq(HsmwDriverClass::getDriverId,id));
                if (CollectionUtil.isEmpty(list)) {
                    return new DataResponse(CommonConstants.ResponseStatus.STUDY_NOT_CONPLETE, null);
                } else {
                    for (HsmwDriverClass hsmwDriverClass : list) {
                        if (!StringUtils.equals("100", hsmwDriverClass.getProgress())) {
                            return new DataResponse(CommonConstants.ResponseStatus.STUDY_NOT_CONPLETE, null);
                        }
                    }
                }
            }*/
            HashMap res = new HashMap();
            res.put("id",id);
            res.put("workStatus",workStatus);
            HsmwUserDriver hsmwUserDriver =hsmwUserDriverService.getById(id);
            hsmwUserDriver.setWorkStatus(workStatus);
            hsmwUserDriverService.updateById(hsmwUserDriver);
            HsmwHtnUser  currentUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
            HsmwDriverUser driverUser = hsmwDriverUserService.getById(hsmwUserDriver.getUserId());
            String[] params = new String[]{currentUser.getName(),workStatus};
            SendSmsUtil.sendSmsWithParam(appId, appKey, params, driverChangeWorkStatus, smsSign, driverUser.getUsername());

            String msg ="您的司机状态被调度"+currentUser.getName()+"切换为"+workStatus+"，如有问题及时与调度联系。";
            TencentPushUtils.pushMsg(msg,driverUser.getUsername(),"");
            //存储系统消息
            HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
            hsmwDriverNews.setUserId(driverUser.getId());
            hsmwDriverNews.setMessage(msg);
            hsmwDriverNews.setAlreadyRead("0");
            hsmwDriverNewsService.save(hsmwDriverNews);

            System.out.println(msg);
            return new DataResponse(SUCCESS,res);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }
    @Log(title = "混天凝APP 批量修改司机改变状态", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 批量修改司机改变状态", notes = "批量修改司机改变状态", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "司机id", name = "id", dataType = "String"),
            @ApiImplicitParam(value = "工作状态 切换为 '接单中'或者 '休息中'  ", name = "workStatus", dataType = "String")
    })
    @PostMapping("updateBatchDriverWorkStatus")
    public DataResponse updateBatchDriverWorkStatus(String ids,String  workStatus){
        try {
            if(StringUtils.isNotBlank(ids)){
                String[] driverIds = ids.split(",");
                if(driverIds.length>0){
                    for(String  id: driverIds){

                        if(StringUtils.equals(workStatus,CommonConstants.DRIVER_FREE)){
                            String key = "driver:status:"+id;
                            redisTemplate.opsForValue().set(key,LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                        }
                        HsmwUserDriver hsmwUserDriver =hsmwUserDriverService.getById(id);
                        hsmwUserDriver.setWorkStatus(workStatus);
                       /* if(CommonConstants.DRIVER_ACCEPT_ORDER.equals(workStatus)){
                            List<HsmwDriverClass> list = hsmwDriverClassService.list(new LambdaQueryWrapper<HsmwDriverClass>().eq(HsmwDriverClass::getDriverId,id));
                            if (CollectionUtil.isEmpty(list)) {
                                return new DataResponse(CommonConstants.ResponseStatus.STUDY_NOT_CONPLETE, null);
                            } else {
                                for (HsmwDriverClass hsmwDriverClass : list) {
                                    if (!StringUtils.equals("100", hsmwDriverClass.getProgress())) {
                                        return new DataResponse(CommonConstants.ResponseStatus.STUDY_NOT_CONPLETE, null);
                                    }
                                }
                            }
                            *//*HsmwUserDriver driverInfo =hsmwUserDriverService.getById(id);
                            if(StringUtils.isNotBlank(driverInfo.getVehicleId())){
                                // 根据车辆id 查询一下有没有进行中的订单 如果车辆有订单 则 把司机的状态更改为工作中
                                HashMap params = new HashMap();
                                params.put("vehicleId",hsmwUserDriver.getVehicleId());
                                if(params.get("vehicleId") != null){
                                    List<CurrentOrderInfoVO> orderList = hsmwOrderVehicleRelationService.getGoingOrderListByParam(params);
                                    if(CollectionUtil.isNotEmpty(orderList)){
                                        hsmwUserDriver.setWorkStatus(CommonConstants.DRIVER_WORK);
                                    }
                                }
                            }*//*
                        }*/
                        hsmwUserDriverService.updateById(hsmwUserDriver);
                        HsmwHtnUser  currentUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
                        HsmwDriverUser driverUser = hsmwDriverUserService.getById(hsmwUserDriver.getUserId());
                        String[] params = new String[]{currentUser.getName(),workStatus};
                        SendSmsUtil.sendSmsWithParam(appId, appKey, params, driverChangeWorkStatus, smsSign, driverUser.getUsername());
                        String msg ="您的司机状态被调度"+currentUser.getName()+"切换为"+workStatus+"，如有问题及时与调度联系。";
                        System.out.println(msg);
                        TencentPushUtils.pushMsg(msg,driverUser.getUsername(),"");
                        //存储系统消息
                        HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
                        hsmwDriverNews.setUserId(driverUser.getId());
                        hsmwDriverNews.setMessage(msg);
                        hsmwDriverNews.setAlreadyRead("0");
                        hsmwDriverNewsService.save(hsmwDriverNews);

                    }
                }
            }
            HashMap res = new HashMap();
            res.put("id",ids);
            res.put("workStatus",workStatus);
            return new DataResponse(SUCCESS,res);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }


    @Log(title = "混天凝APP 批量修改司机的平台接单状态", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 批量修改司机的平台接单状态", notes = "批量修改司机的平台接单状态", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "司机id", name = "id", dataType = "String"),
            @ApiImplicitParam(value = "接单状态 切换为  true 或者 false  ", name = "receiveFlag", dataType = "String")
    })
    @PostMapping("updateBatcVehicleReceiveFlag")
    public DataResponse updateBatcVehicleReceiveFlag(String ids,boolean  receiveFlag){
        try {
            if(StringUtils.isNotBlank(ids)){
                String[] vehicleIds = ids.split(",");
                if(vehicleIds.length>0){
                    for(String  id: vehicleIds){
                        HsmwVehicle hsmwVehicle =hsmwVehicleService.getById(id);
                        hsmwVehicle.setReceiveFlag(receiveFlag);
                        hsmwVehicleService.updateById(hsmwVehicle);
                    }
                }
            }
            HashMap res = new HashMap();
            res.put("ids",ids);
            res.put("receiveFlag",receiveFlag);
            return new DataResponse(SUCCESS,res);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }



    @Log(title = "混天凝APP 修改订单是否允许工长从平台叫车", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 修改订单是否允许工长从平台叫车", notes = "修改订单是否允许工长从平台叫车", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "订单ID", name = "orderId", dataType = "String"),
            @ApiImplicitParam(value = "是否允许工长从平台叫车  切换为  0 或者 1  ", name = "receiveFlag", dataType = "String")
    })
    @PostMapping("updateOrderReceiveFlag")
    public DataResponse updateOrderReceiveFlag(String orderId,String  receiveFlag,String requestId){
        HsmwHtnUser currentUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
        try {
            if(StringUtils.isNotBlank(orderId)){
                if(CommonConstants.YES.equals(receiveFlag)){
                    HsmwOrder hsmwOrder = hsmwOrderService.getHsmwOrderById(orderId);
                    double expectVolume = new BigDecimal(StringUtils.isNotBlank(hsmwOrder.getExpectVolume()) ? hsmwOrder.getExpectVolume() : "0.00").doubleValue();
                    BigDecimal availableLimit = new BigDecimal("0.0");
                    if (HtnUserTypeEnum.COMPANY.getValue().equals(currentUser.getType())) {
                        HsmwLeasingCompany company = hsmwLeasingCompanyService.getById(currentUser.getOwnCompanyId());
                        availableLimit = company.getAvailableLimit();
                    }
                    if (HtnUserTypeEnum.CONCRETE.getValue().equals(currentUser.getType())) {
                        HsmwConcretePlantInfo company = hsmwConcretePlantInfoMapper.selectById(currentUser.getOwnCompanyId());
                        availableLimit = company.getAvailableLimit();
                    }
                    //只有平台叫泵 在开通了并开启了以后 才需要计算 。首先计算出 所选择的泵车的类型和型号所对应的价格最高者
                    List<HsmwOrderVehicleRequest> requestList = hsmwOrderVehicleRequestService.list(new LambdaQueryWrapper<HsmwOrderVehicleRequest>()
                            .eq(HsmwOrderVehicleRequest::getOrderId, orderId));
                    BigDecimal settlePrice = hsmwOrderService.getMaxPrice(requestList, currentUser);
                    Double settlePriceDouble = settlePrice.doubleValue();
                    Double availableLimitDouble = 0.00;
                    if (StringUtils.isNotNull(availableLimit)) {
                        availableLimitDouble = availableLimit.doubleValue();
                    }
                    //每次下单时判断当前订单的预计方量是否小于{剩余额度-（单价*100）}/单价
                    //如果余额不足就返回提示。
                    if (0.00 != settlePriceDouble && (availableLimitDouble - (settlePriceDouble * 100)) / settlePriceDouble < expectVolume) {
                        HashMap res = new HashMap();
                        res.put("code", 111);
                        return new DataResponse(CommonConstants.ResponseStatus.BALANCE_NOT_ENOUGH, res);
                    }
                    hsmwOrder.setIfSelfChoose(receiveFlag);
                    hsmwOrderService.updateById(hsmwOrder);
                }

            }
            return new DataResponse(SUCCESS,"操作成功");
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }


    @Log(title = "混天凝APP 更换司机", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 更换司机", notes = "更换司机", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "司机id", name = "id", dataType = "String"),
            @ApiImplicitParam(value = "新选中司机id", name = "newId", dataType = "String"),
    })
    @PostMapping("/changeVehicleDriver")
    public DataResponse changeVehicleDriver(String id,String  newId){
        try {

            HsmwBanDriver banDriver = hsmwBanDriverService.getOne(new LambdaQueryWrapper<HsmwBanDriver>().eq(HsmwBanDriver::getDriverId, newId).eq(HsmwBanDriver::getStatus, "1").last("LIMIT 1"));
            if (StringUtils.isNotNull(banDriver)) {
                return new DataResponse(CommonConstants.ResponseStatus.BAN_DRIVER_MESSAGE,null);
            }
            //有进行中订单
            HsmwUserDriver hsmwUserDriver =hsmwUserDriverService.getById(id);
            if(CommonConstants.DRIVER_WORK.equals(hsmwUserDriver.getWorkStatus())){
                List<HsmwUserDriver> userDrivers = hsmwUserDriverService.list(new LambdaQueryWrapper<HsmwUserDriver>()
                        .eq(HsmwUserDriver::getVehicleId, hsmwUserDriver.getVehicleId())
                        .eq(HsmwUserDriver::getWorkStatus,CommonConstants.DRIVER_WORK));
                if(CollectionUtil.isNotEmpty(userDrivers) && userDrivers.size() == 1){
                    return new DataResponse(CommonConstants.ResponseStatus.ONLY_ONE_DRIVER,null);
                }
            }
            //首先将这个司机车辆滞空
            String vehicleId = hsmwUserDriver.getVehicleId();
            hsmwUserDriver.setVehicleId(null);
            hsmwUserDriver.setWorkStatus(CommonConstants.CHANGING_CARS);
            hsmwUserDriverService.updateById(hsmwUserDriver);
            HsmwVehicle vehicle = hsmwVehicleService.getVehicleById(vehicleId);
            HsmwHtnUser  currentUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
            HsmwDriverUser driverUser = hsmwDriverUserService.getById(hsmwUserDriver.getUserId());
            String[] params = new String[]{currentUser.getName(),vehicle.getVehiclePlate()};
            SendSmsUtil.sendSmsWithParam(appId, appKey, params, driverRemoveVehicle, smsSign, driverUser.getUsername());
            String msg = "您已被"+currentUser.getName()+"从"+vehicle.getVehiclePlate()+"中移出，目前处于没车状态";
            TencentPushUtils.pushMsg(msg,driverUser.getUsername(),"");
            //存储系统消息
            HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
            hsmwDriverNews.setUserId(driverUser.getId());
            hsmwDriverNews.setMessage(msg);
            hsmwDriverNews.setAlreadyRead("0");
            hsmwDriverNewsService.save(hsmwDriverNews);



            //同时将新司机的车辆ID变为被更换的司机的车辆ID
            HsmwUserDriver newDriver = hsmwUserDriverService.getById(newId);
            newDriver.setWorkStatus(CommonConstants.DRIVER_FREE);
            newDriver.setVehicleId(vehicleId);
            hsmwUserDriverService.updateById(newDriver);
            HsmwDriverUser driverUser1 = hsmwDriverUserService.getById(newDriver.getUserId());
            String[] params1 = new String[]{currentUser.getName(),vehicle.getVehiclePlate(),vehicle.getVehicleType()+" "+vehicle.getVehicleModel()};
            SendSmsUtil.sendSmsWithParam(appId, appKey, params1, driverChangeVehicle, smsSign, driverUser1.getUsername());
            String msg1 ="您所绑定车辆被调度"+currentUser.getName()+"调整为"+vehicle.getVehiclePlate()+"型号为"+vehicle.getVehicleType()+" "+vehicle.getVehicleModel();
            System.out.println(msg1);
            TencentPushUtils.pushMsg(msg1,driverUser1.getUsername(),"");
            //存储系统消息
            HsmwDriverNews hsmwDriverNews1 = new HsmwDriverNews();
            hsmwDriverNews1.setUserId(driverUser1.getId());
            hsmwDriverNews1.setMessage(msg1);
            hsmwDriverNews1.setAlreadyRead("0");
            hsmwDriverNewsService.save(hsmwDriverNews1);


            HashMap res = new HashMap();
            res.put("id",id);
            res.put("newId",newId);
            return new DataResponse(SUCCESS,res);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }

    @Log(title = "混天凝APP 添加司机", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 添加司机", notes = "添加司机", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "车辆ID", name = "vehicleId", dataType = "String"),
            @ApiImplicitParam(value = "新选中司机id", name = "newId", dataType = "String"),
    })
    @PostMapping("addVehicleDriver")
    public DataResponse addVehicleDriver(String id,String  newId){
        try {

            HsmwBanDriver banDriver = hsmwBanDriverService.getOne(new LambdaQueryWrapper<HsmwBanDriver>().eq(HsmwBanDriver::getDriverId, newId).eq(HsmwBanDriver::getStatus, "1").last("LIMIT 1"));
            if (StringUtils.isNotNull(banDriver)) {
                return new DataResponse(CommonConstants.ResponseStatus.BAN_DRIVER_MESSAGE,null);
            }
            HsmwUserDriver newDriver = hsmwUserDriverService.getById(newId);
            HsmwVehicle vehicle =hsmwVehicleService.getVehicleById(id);
            List<HsmwUserDriver> drivers = hsmwUserDriverService.list(new LambdaQueryWrapper<HsmwUserDriver>()
                    .eq(HsmwUserDriver::getVehicleId,vehicle.getId()));
            if(Integer.parseInt(vehicle.getMaxDriverNumber())>drivers.size()){
                //同时将新司机的车辆ID变为被更换的司机的车辆ID
/*
                if(CommonConstants.CHANGING_CARS.equals(newDriver.getWorkStatus())){
*/
                newDriver.setWorkStatus(CommonConstants.DRIVER_FREE);
                /*}*/
                newDriver.setId(newId);
                newDriver.setVehicleId(id);
                hsmwUserDriverService.updateById(newDriver);
            }else {
                return new DataResponse(CommonConstants.ResponseStatus.VEHICLE_DRIVER_COUNT_FULL,null);
            }
            HashMap res = new HashMap();
            res.put("id",id);
            res.put("newId",newId);

            HsmwHtnUser  currentUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
            HsmwDriverUser driverUser = hsmwDriverUserService.getById(newDriver.getUserId());
            String[] params = new String[]{currentUser.getName(),vehicle.getVehiclePlate(),vehicle.getVehicleType()+" "+vehicle.getVehicleModel()};
            SendSmsUtil.sendSmsWithParam(appId, appKey, params, driverChangeVehicle, smsSign, driverUser.getUsername());
            String msg ="您所绑定车辆被调度"+currentUser.getName()+"调整为"+vehicle.getVehiclePlate()+"型号为"+vehicle.getVehicleType()+" "+vehicle.getVehicleModel();
            System.out.println(msg);
            TencentPushUtils.pushMsg(msg,driverUser.getUsername(),"");

            //存储系统消息
            HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
            hsmwDriverNews.setUserId(driverUser.getId());
            hsmwDriverNews.setMessage(msg);
            hsmwDriverNews.setAlreadyRead("0");
            hsmwDriverNewsService.save(hsmwDriverNews);

            return new DataResponse(SUCCESS,res);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }



    @Log(title = "混天凝APP 查询全部的司机", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 查询全部的司机", notes = "添加司机", produces = "application/json")
    @PostMapping("queryAllDriverInfo")
    public DataResponse queryAllDriverInfo(){
        try {
            HsmwHtnUser currentHtnUser= currentHsmwUserUtils.getCurrentHtnUserInfo();
            HashMap param= new HashMap();
            param.put("companyId",currentHtnUser.getOwnCompanyId());
            List<DriverInfoVO> driverCountVOS = hsmwOrderMapper.findDriverListByehicleId(param);
            return new DataResponse(SUCCESS,driverCountVOS);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }



    @Log(title = "混天凝APP 更新车辆信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 更新车辆信息", notes = "更新车辆信息", produces = "application/json")
    @PostMapping("updateVehicleInfo")
    public DataResponse updateVehicleInfo(@RequestBody  HsmwVehicle  hsmwVehicle){
        try {

            hsmwVehicleService.updateById(hsmwVehicle);
            //车辆更新完信息之后 查看一下车辆证件是否都在保，如果都在保那么直接将车辆状态改为 空闲中
            HsmwVehicle currentVehicle  =hsmwVehicleService.getVehicleById(hsmwVehicle.getId());
            if(CommonConstants.VEHICLE_EXPIRATION.equals(currentVehicle.getWorkStatus())){
                if((StringUtils.isNotNull(currentVehicle.getDrivingLicenseTime()) && currentVehicle.getDrivingLicenseTime().isAfter(LocalDate.now()))&& (StringUtils.isNotNull(currentVehicle.getCommercialInsuranceTime()) && currentVehicle.getCommercialInsuranceTime().isAfter(LocalDate.now())) &&
                        (StringUtils.isNotNull(currentVehicle.getCompuTrafficTime()) && currentVehicle.getCompuTrafficTime().isAfter(LocalDate.now()))){
                    List<HsmwOrderVehicleRelation> relationList = hsmwOrderVehicleRelationService.list(new LambdaQueryWrapper<HsmwOrderVehicleRelation>()
                            .eq(HsmwOrderVehicleRelation::getVehicleId,hsmwVehicle.getId())
                            .in(HsmwOrderVehicleRelation::getOrderStatus,ChildOrderStatusEnum.RECEIVED.getValue(),ChildOrderStatusEnum.STARTUP.getValue(),ChildOrderStatusEnum.ARRIVED.getValue(),ChildOrderStatusEnum.UNRECEIVED.getValue()));
                    if(CollectionUtil.isNotEmpty(relationList)){
                        currentVehicle.setWorkStatus(CommonConstants.VEHICLE_WORK);
                    }else{
                        currentVehicle.setWorkStatus(CommonConstants.VEHICLE_FREE);
                    }
                    hsmwVehicleService.updateById(currentVehicle);
                }
            }
            return new DataResponse(SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }



    @Log(title = "混天凝APP 获取我的泵送设置信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 获取我的泵送设置信息", notes = "获取我的泵送设置信息", produces = "application/json")
    @PostMapping("getPumpOrderSetup")
    public DataResponse getPumpOrderSetup(){
        try {
            HsmwHtnUser currentUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
            ReceiveOrderVO res = new ReceiveOrderVO();

            if (HtnUserTypeEnum.COMPANY.getValue().equals(currentUser.getType())) {
                HsmwLeasingCompany company = hsmwLeasingCompanyService.getById(currentUser.getOwnCompanyId());
                res.setEnableFlag(company.isEnableFlag());
                res.setOpenFlag( company.isOpenFlag());
                res.setUnSettlementLimit(company.getUnSettlementLimit());
                res.setUnSettlementLimit(company.getSettlementLimit());
                res.setAvailableLimit(company.getAvailableLimit());
                res.setFrozenLimit(company.getFrozenLimit());
            }
            if (HtnUserTypeEnum.CONCRETE.getValue().equals(currentUser.getType())) {
                HsmwConcretePlantInfo company = hsmwConcretePlantInfoMapper.selectById(currentUser.getOwnCompanyId());
                res.setEnableFlag(company.isEnableFlag());
                res.setOpenFlag( company.isOpenFlag());
                res.setUnSettlementLimit(company.getUnSettlementLimit());
                res.setUnSettlementLimit(company.getSettlementLimit());
                res.setAvailableLimit(company.getAvailableLimit());
                res.setFrozenLimit(company.getFrozenLimit());
            }
            return new DataResponse(SUCCESS,res);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }


    @Log(title = "混天凝APP 泵送设置", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 泵送设置", notes = "泵送设置", produces = "application/json")
    @PostMapping("updatePumpOrderSetup")
    public DataResponse updatePumpOrderSetup(Boolean enable){
        HsmwHtnUser currentUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
        try {
            if(HtnUserTypeEnum.COMPANY.getValue().equals(currentUser.getType())){
                HsmwLeasingCompany company = hsmwLeasingCompanyService.getById(currentUser.getOwnCompanyId());
                if(!company.isOpenFlag() && enable){
                    return new DataResponse(CommonConstants.ResponseStatus.NOT_OPEN_NO_ENABLE,"尚未开通平台接单，无法开启");
                }
                company.setEnableFlag(enable);
                hsmwLeasingCompanyService.updateById(company);
            }
            if(HtnUserTypeEnum.CONCRETE.getValue().equals(currentUser.getType())){
                HsmwConcretePlantInfo company = hsmwConcretePlantInfoMapper.selectById(currentUser.getOwnCompanyId());
                if(!company.isOpenFlag() && enable){
                    return new DataResponse(CommonConstants.ResponseStatus.NOT_OPEN_NO_ENABLE,"尚未开通平台接单，无法开启");
                }
                company.setEnableFlag(enable);
                hsmwConcretePlantInfoMapper.updateById(company);
            }
            return new DataResponse(SUCCESS,"开启成功");
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }



    @Log(title = "混天凝APP 获取我的接单设置信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 获取我的接单设置信息", notes = "获取我的接单设置信息", produces = "application/json")
    @PostMapping("getReceiveOrderSetup")
    public DataResponse getReceiveOrderSetup(){
        try {
            HsmwHtnUser currentUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
            ReceiveOrderVO res = new ReceiveOrderVO();
            if (HtnUserTypeEnum.COMPANY.getValue().equals(currentUser.getType())) {
                HsmwLeasingCompany company = hsmwLeasingCompanyService.getById(currentUser.getOwnCompanyId());
                res.setReceiveEnableFlag(company.isReceiveEnableFlag());
                res.setReceiveOpenFlag( company.isReceiveOpenFlag());
            }
            List<HsmwReceiveOrderPrice> receiveOrderPrices = hsmwReceiveOrderPriceMapper.selectList(new LambdaQueryWrapper<HsmwReceiveOrderPrice>()
                    .eq(HsmwReceiveOrderPrice::getCompanyId,currentUser.getOwnCompanyId())
                    .eq(HsmwReceiveOrderPrice::getSettleType,SettlementTypeEnum.RECEIVE_PRICE.getValue())
                    .orderByAsc(HsmwReceiveOrderPrice::getVehicleModel));
            List<HsmwReceiveSubsidyPrice> newReceiveSubsidyPrices = hsmwReceiveSubsidyPriceMapper.selectList(new LambdaQueryWrapper<HsmwReceiveSubsidyPrice>().
                    eq(HsmwReceiveSubsidyPrice::getCompanyId,currentUser.getOwnCompanyId())
                    .eq(HsmwReceiveSubsidyPrice::getSubsidyType,SubsidyTypeEnum.NEW_CAR.getValue())
                    .eq(HsmwReceiveSubsidyPrice::getSettleType,SettlementTypeEnum.RECEIVE_PRICE.getValue())
                    .orderByAsc(HsmwReceiveSubsidyPrice::getCreateTime));
            List<HsmwReceiveSubsidyPrice> nightReceiveSubsidyPrices = hsmwReceiveSubsidyPriceMapper.selectList(new LambdaQueryWrapper<HsmwReceiveSubsidyPrice>().
                    eq(HsmwReceiveSubsidyPrice::getCompanyId,currentUser.getOwnCompanyId())
                    .eq(HsmwReceiveSubsidyPrice::getSubsidyType,SubsidyTypeEnum.NIGHT_WORK.getValue())
                    .eq(HsmwReceiveSubsidyPrice::getSettleType,SettlementTypeEnum.RECEIVE_PRICE.getValue())
                    .orderByAsc(HsmwReceiveSubsidyPrice::getCreateTime));

            res.setReceivePrices(receiveOrderPrices);
            res.setNewCarReceiveSubsidyPrices(newReceiveSubsidyPrices);
            res.setNightReceiveSubsidyPrices(nightReceiveSubsidyPrices);
            return new DataResponse(SUCCESS,res);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }


    @Log(title = "混天凝APP 接单设置", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 接单设置", notes = "接单设置", produces = "application/json")
    @PostMapping("updateReceiveOrderSetup")
    public DataResponse updateReceiveOrderSetup(Boolean enable){
        HsmwHtnUser currentUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
        try {
            if(HtnUserTypeEnum.COMPANY.getValue().equals(currentUser.getType())){
                HsmwLeasingCompany company = hsmwLeasingCompanyService.getById(currentUser.getOwnCompanyId());
                if(!company.isReceiveOpenFlag() && enable){
                    return new DataResponse(CommonConstants.ResponseStatus.NOT_OPEN_NO_ENABLE,"尚未开通平台接单，无法开启");
                }
                company.setReceiveEnableFlag(enable);
                hsmwLeasingCompanyService.updateById(company);
            }
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
        return new DataResponse(SUCCESS,"操作成功");
    }



    @Log(title = "混天凝APP 我的钱包信息 ", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 我的钱包信息", notes = "我的钱包信息", produces = "application/json")
    @PostMapping("getPayBagInfo")
    public DataResponse getPayBagInfo(){
        HsmwHtnUser currentUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
        try {
            ReceiveOrderVO vo = new ReceiveOrderVO();
            if(HtnUserTypeEnum.COMPANY.getValue().equals(currentUser.getType())){
                HsmwLeasingCompany company = hsmwLeasingCompanyService.getById(currentUser.getOwnCompanyId());
                    vo.setUnSettlementLimit(company.getUnSettlementLimit());
                    vo.setSettlementLimit(company.getSettlementLimit());
                    vo.setAvailableLimit(company.getAvailableLimit());
                    vo.setFrozenLimit(company.getFrozenLimit());
                }
            if(HtnUserTypeEnum.CONCRETE.getValue().equals(currentUser.getType())){
                HsmwConcretePlantInfo company = hsmwConcretePlantInfoMapper.selectById(currentUser.getOwnCompanyId());
                vo.setUnSettlementLimit(company.getUnSettlementLimit());
                vo.setSettlementLimit(company.getSettlementLimit());
                vo.setAvailableLimit(company.getAvailableLimit());
                vo.setFrozenLimit(company.getFrozenLimit());
            }
            HashMap param = new HashMap();
            param.put("companyId",currentUser.getOwnCompanyId());
            param.put("settleStatus",SettlementStatusEnum.FROZEN.getValue());
            List<HtnSettleOrderDetailVo> htnSettleOrderDetailVos = hsmwOrderMapper.selectSettleOrderListByParam(param);
            HtnSettleOrderCountVo frozenSettleCount = hsmwOrderMapper.selectFrozenCountByParam(param);

            vo.setHtnFrozenOrderList(htnSettleOrderDetailVos);
            vo.setFrozenVolume(StringUtils.isNotNull(frozenSettleCount)?frozenSettleCount.getDriverVolumeSum():0.00);

            param.put("settleStatus",SettlementStatusEnum.ENSURE.getValue());
            HtnSettleOrderCountVo unsettleFrozenCount = hsmwOrderMapper.selectFrozenCountByParam(param);
            List<HtnSettleOrderDetailVo> unSettleOrderDetailVos = hsmwOrderMapper.selectSettleOrderListByParam(param);

            vo.setUnSettleOrderList(unSettleOrderDetailVos);
            vo.setUnSettlementVolume(StringUtils.isNotNull(unsettleFrozenCount)?unsettleFrozenCount.getDriverVolumeSum():0.00);

            return new DataResponse(SUCCESS,vo);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }


    @Log(title = "混天凝APP 修改项目人员角色", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 修改项目人员角色 邀请ID：inviteId  type  0 改为工长；1 改为项目负责人", notes = "修改项目人员角色", produces = "application/json")
    @PostMapping("updateForemanRoleInfo")
    public DataResponse updateForemanRoleInfo(String inviteId,String type){
        HsmwHtnUser currentUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
        try {
            HsmwInviteRecord inviteRecord =hsmwInviteRecordService.getById(inviteId);
            HsmwForcemanItem forcemanItem = new HsmwForcemanItem();

            //如果是改为工长
            if(CommonConstants.NO.equals(type)){
                //如果当前用户是 公司用户 首先将该邀请成功记录的 邀请类型改为公司 邀请工长
                    if(HtnUserTypeEnum.COMPANY.getValue().equals(currentUser.getType())){
                    inviteRecord.setInviteType(InviteTypeEnum.COMPANY_INVITE_FOREMAN.getValue());
                }
                // 如果当前用户是 搅拌站用户 首先将该邀请成功记录的 邀请类型改为搅拌站  邀请工长
                if(HtnUserTypeEnum.CONCRETE.getValue().equals(currentUser.getType())){
                    inviteRecord.setInviteType(InviteTypeEnum.CONCRETE_INVITE_FOREMAN.getValue());
                }
                //同时需要将 工长项目关联表中的 权限类型改为工长
                forcemanItem.setRoleType(ForemanRoleEnum.FOREMEN.getValue());

            }else {
                //如果当前用户是 公司用户 首先将该邀请成功记录的 邀请类型改为公司 邀请项目负责人
                if(HtnUserTypeEnum.COMPANY.getValue().equals(currentUser.getType())){
                    inviteRecord.setInviteType(InviteTypeEnum.COMPANY_INVITE_PROJECTMAN.getValue());
                }
                // 如果当前用户是 搅拌站用户 首先将该邀请成功记录的 邀请类型改为搅拌站  邀请项目负责人
                if(HtnUserTypeEnum.CONCRETE.getValue().equals(currentUser.getType())){
                    inviteRecord.setInviteType(InviteTypeEnum.CONCRETE_INVITE_PROJECTMAN.getValue());
                }
                //同时需要将 工长项目关联表中的 权限类型改为项目负责人
                forcemanItem.setRoleType(ForemanRoleEnum.PROJECTMAN.getValue());

            }
            hsmwInviteRecordService.updateById(inviteRecord);
            hsmwForcemanItemMapper.update(forcemanItem,new LambdaQueryWrapper<HsmwForcemanItem>()
                    .eq(HsmwForcemanItem::getForcemanId,inviteRecord.getInviteeUserId())
                    .eq(HsmwForcemanItem::getItemId,inviteRecord.getItemId()));
            return new DataResponse(SUCCESS,"操作成功");
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }


    @Log(title = "混天凝APP 查询项目的合作公司", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 查询项目的合作公司 项目ID：  itemId", notes = "查询项目的合作公司", produces = "application/json")
    @PostMapping("queryCorperates")
    public DataResponse queryCorperates(String itemId){
        HsmwHtnUser currentUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
        try {
            HashMap res = new HashMap();
            HsmwItem item = hsmwItemService.getHsmwItemById(itemId);
            res.put("companyName",item.getVehicleUnitName());
            if(StringUtils.isNotBlank(item.getVehicleUnitId()) && item.getVehicleUnitId().equals(currentUser.getOwnCompanyId())){
                res.put("flag",1);
            }else {
                res.put("flag",0);
            }
            return new DataResponse(SUCCESS,res);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }


    @Log(title = "混天凝APP 查询指定下单选择的车辆列表", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 查询指定下单选择的车辆列表", notes = "查询指定下单选择的司机列表", produces = "application/json")
    @PostMapping("queryAvaliableVehiclesInfo")
    public DataResponse queryAvaliableVehiclesInfo(){
        HsmwHtnUser currentUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
        try {
            HashMap res = new HashMap();
            res.put("companyId",currentUser.getOwnCompanyId());
            res.put("userId",currentUser.getId());
            boolean openFlag=false;
            boolean enableFlag=false;
            if(HtnUserTypeEnum.COMPANY.getValue().equals(currentUser.getType())){
                HsmwLeasingCompany company =hsmwLeasingCompanyService.getById(currentUser.getOwnCompanyId());
                openFlag=company.isOpenFlag();
                enableFlag=company.isEnableFlag();
            }
            if(HtnUserTypeEnum.CONCRETE.getValue().equals(currentUser.getType())){
                HsmwConcretePlantInfo company =hsmwConcretePlantInfoMapper.selectById(currentUser.getOwnCompanyId());
                openFlag=company.isOpenFlag();
                enableFlag=company.isEnableFlag();
            }
            res.put("openFlag",openFlag);
            res.put("enableFlag",enableFlag);
            res.put("companyId",currentUser.getOwnCompanyId());
            List<VehicleInfoVO> aviliableVehicles = hsmwVehicleMapper.queryAvaliableVehiclesInfo(res);
            for (VehicleInfoVO vehicle : aviliableVehicles) {
                HashMap param = new HashMap();
                param.put("vehicleId", vehicle.getVehicleId());
                List<DriverInfoVO> driverCountVOS = hsmwOrderMapper.findDriverListByehicleId(param);
                vehicle.setDriverCountVOS(driverCountVOS);
                //如果是收藏的车辆我需要判断一下 车辆是不是外租泵
                if(VehicleOwnTypeEnum.COLLECT.getValue().equals(vehicle.getOwnType())){
                    param.put("companyId",currentUser.getOwnCompanyId());
                    List<HsmwVehicle> vehicles = hsmwVehicleService.checkIfPlateformVehicles(param);
                    if(CollectionUtil.isNotEmpty(vehicles)){
                        vehicle.setOutsideLeasingFlag(CommonConstants.YES);
                    }else {
                        vehicle.setOutsideLeasingFlag(CommonConstants.NO);
                    }
                }
            }
            res.put("vehicles",aviliableVehicles);
            System.out.println(JSON.toJSONString(res));
            return new DataResponse(SUCCESS,res);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }


    @ApiOperation(value = "查询邀请项目负责人和工长的记录 ",notes = "查询邀请项目负责人和工长的记录 ",produces = "application/json")
@PostMapping("/queryInviteForemanInfoList")
    public DataResponse queryInviteInfoList(String  itemId){
        //当前用户
        HsmwHtnUser currentHtnUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
        HashMap res = new HashMap();
        if(HtnUserTypeEnum.COMPANY.getValue().equals(currentHtnUser.getType())){
            HashMap param = new HashMap();

            List<String> typeList = new ArrayList<>();
            typeList.add(InviteTypeEnum.COMPANY_INVITE_FOREMAN.getValue());
            typeList.add(InviteTypeEnum.PROJECTMAN_INVITE_FOREMAN.getValue());
            param.put("itemId",itemId);
            param.put("inviteTypeList",typeList);

            //param.put("userId",currentHtnUser.getId());
            param.put("itemId",itemId);
            List<HsmwInviteRecord> foremanRecords = hsmwInviteRecordMapper.queryInviteList(param);
            res.put("foremanRecords",foremanRecords);
            param.remove("inviteTypeList");

            param.put("inviteType",InviteTypeEnum.COMPANY_INVITE_PROJECTMAN.getValue());
            List<HsmwInviteRecord> projectManRecords = hsmwInviteRecordMapper.queryInviteList(param);
            res.put("projectManRecords",projectManRecords);
        }
        if(HtnUserTypeEnum.CONCRETE.getValue().equals(currentHtnUser.getType())){

            HashMap param = new HashMap();

            List<String> typeList = new ArrayList<>();
            typeList.add(InviteTypeEnum.CONCRETE_INVITE_FOREMAN.getValue());
            typeList.add(InviteTypeEnum.PROJECTMAN_INVITE_FOREMAN.getValue());
            //param.put("userId",currentHtnUser.getId());
            param.put("itemId",itemId);
            param.put("inviteTypeList",typeList);
            List<HsmwInviteRecord> foremanRecords =hsmwInviteRecordMapper.queryInviteList(param);
            res.put("foremanRecords",foremanRecords);
            param.remove("inviteTypeList");
            param.put("inviteType",InviteTypeEnum.CONCRETE_INVITE_PROJECTMAN.getValue());
            List<HsmwInviteRecord> projectManRecords =hsmwInviteRecordMapper.queryInviteList(param);
            res.put("projectManRecords",projectManRecords);
        }
        if(HtnUserTypeEnum.FOREMAN.getValue().equals(currentHtnUser.getType())){
            HashMap param = new HashMap();
            param.put("itemId",itemId);
            if(ForemanRoleEnum.FOREMEN.getValue().equals(currentHtnUser.getRoleType())){
                param.put("inviteStatus",InviteStatusEnum.RECEIVED.getValue());
            }
            List<String> typeList = new ArrayList<>();
            typeList.add(InviteTypeEnum.CONCRETE_INVITE_FOREMAN.getValue());
            typeList.add(InviteTypeEnum.COMPANY_INVITE_FOREMAN.getValue());
            typeList.add(InviteTypeEnum.PROJECTMAN_INVITE_FOREMAN.getValue());
            param.put("inviteTypeList",typeList);
            List<HsmwInviteRecord> foremanRecords =hsmwInviteRecordMapper.queryInviteList(param);
            res.put("foremanRecords",foremanRecords);
            List<String> typeList1 = new ArrayList<>();
            typeList1.add(InviteTypeEnum.CONCRETE_INVITE_PROJECTMAN.getValue());
            typeList1.add(InviteTypeEnum.COMPANY_INVITE_PROJECTMAN.getValue());
            param.put("inviteTypeList",typeList1);
            List<HsmwInviteRecord> projectManRecords =hsmwInviteRecordMapper.queryInviteList(param);
            res.put("projectManRecords",projectManRecords);
        }
        return  new DataResponse(res);
    }



    @Log(title = "混天凝APP 查询负责人", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 查询负责人", notes = "查询负责人", produces = "application/json")
    @PostMapping("queryLeasingPerson")
    public DataResponse queryLeasingPerson(){
        HsmwHtnUser currentUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
        try {
            HashMap res = new HashMap();
            res.put("companyId",currentUser.getOwnCompanyId());
            List<HsmwHtnUser> hsmwHtnUsers = hsmwHtnUserService.list(new LambdaQueryWrapper<HsmwHtnUser>()
                    .eq(HsmwHtnUser::getOwnCompanyId,currentUser.getOwnCompanyId())
                    .eq(HsmwHtnUser::getRoleType,HtnUserRoleEnum.LEADING.getValue()));
            HsmwHtnUser leadingUser=new HsmwHtnUser();
            if(CollectionUtil.isNotEmpty(hsmwHtnUsers)){
                leadingUser = hsmwHtnUsers.get(0);
            }
            return new DataResponse(leadingUser);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }

    @ApiOperation(value = "fasong", notes = "查看司机投诉信息", produces = "application/json")
    @PostMapping("/fasong")
    public DataResponse fasong (String userName){
        WebSocketReturnVO webSocketReturnVO = new WebSocketReturnVO();
        webSocketReturnVO.setStatus(WebsocketTypeEnum.ZERO_ORDER.getValue());
        webSocketReturnVO.setMessage("您填写的方量是0m³，系统为您判断成为空跑订单。");
        String returnJson = JSONObject.toJSON(webSocketReturnVO).toString();
        webSocket.AppointSending(userName, returnJson);
        return new DataResponse();
    }

    @Log(title = "混天凝APP 查询泵送服务提供商", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 查询泵送服务提供商", notes = "查询泵送服务提供商", produces = "application/json")
    @PostMapping("pumpServiceProvider")
    public DataResponse pumpServiceProvider(String itemId){
        HsmwHtnUser currentUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
        try {
            HashMap res = new HashMap();
            res.put("companyId",currentUser.getOwnCompanyId());
            List<HsmwHtnUser> hsmwHtnUsers = hsmwHtnUserService.list(new LambdaQueryWrapper<HsmwHtnUser>()
                    .eq(HsmwHtnUser::getOwnCompanyId,currentUser.getOwnCompanyId())
                    .eq(HsmwHtnUser::getRoleType,HtnUserRoleEnum.LEADING.getValue()));
            HsmwHtnUser leadingUser=new HsmwHtnUser();
            if(CollectionUtil.isNotEmpty(hsmwHtnUsers)){
                leadingUser = hsmwHtnUsers.get(0);
            }
            return new DataResponse(leadingUser);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }



    @Log(title = "混天凝APP 项目管理页面  查询指定项目的邀请绑定搅拌站信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP  项目管理页面 查询指定项目的邀请的绑定搅拌站信息", notes = "查询指定项目的邀请的绑定搅拌站信息", produces = "application/json")
    @PostMapping("queryConcreteInfoByItemId")
    public DataResponse queryConcreteInfoByItemId(String itemId){
        try {
           List<HsmwInviteRecord> records = hsmwInviteRecordService.list(new LambdaQueryWrapper<HsmwInviteRecord>()
                   .eq(HsmwInviteRecord::getInviteType,InviteTypeEnum.ITEM_INVITE_CONCRETE.getValue())
                   .eq(HsmwInviteRecord::getItemId,itemId));
            return new DataResponse(records);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }

    @Log(title = "混天凝APP 下单页面 查询 搅拌站邀请信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 下单页面 查询 搅拌站邀请信息", notes = "下单页面 查询 搅拌站邀请信息", produces = "application/json")
    @PostMapping("queryInviteConcreteInfoByItemId")
    public DataResponse queryInviteConcreteInfoByItemId(String itemId){
        try {
            HsmwItem itemInfo = hsmwItemService.getHsmwItemById(itemId);
            if(StringUtils.isNull(itemInfo)){
                return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您输入的项目信息不存在");
            }
            HashMap param = new HashMap();
            HsmwHtnUser currentUser = currentHsmwUserUtils.getCurrentHtnUserInfo();
            if(HtnUserTypeEnum.CONCRETE.getValue().equals(currentUser.getType())){
                param.put("plantId",currentUser.getOwnCompanyId());
            }
            param.put("itemId",itemId);
            List<HsmwConcretePlantInfo> concretePlantInfos = hsmwConcretePlantInfoMapper.selectInvitePlantInfos(param);
            //如果是搅拌站用户
            for (HsmwConcretePlantInfo info :concretePlantInfos){
                HashMap calculateParam = new HashMap();
                calculateParam.put("origin", itemInfo.getLng()+","+itemInfo.getLat());
                calculateParam.put("destination", info.getLng()+","+info.getLat());
                Long mapTimeAndDistance = GaoDeInfoUtils.calculateDistance(calculateParam);
                double distence = mapTimeAndDistance / 1000;
                System.err.println("距离--->" + distence);
                info.setConcretePlantDistance(StringUtils.isNull(distence)? 0:distence);
            }
            return new DataResponse(concretePlantInfos);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }

    @Log(title = "混天凝APP 项目管理 可以邀请搅拌站信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 项目管理 查询指定项目的可以邀请的搅拌站信息", notes = "查询指定项目的可以邀请的搅拌站信息", produces = "application/json")
    @PostMapping("queryAvaiableConcreteInfoByItemId")
    public DataResponse queryAvaiableConcreteInfoByItemId(String itemId){
        try {
            HsmwItem itemInfo = hsmwItemService.getHsmwItemById(itemId);
            if(StringUtils.isNull(itemInfo)){
                return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您输入的项目信息不存在");
            }
            List<HsmwConcretePlantInfo> concretePlantInfos = hsmwConcretePlantInfoMapper.selectAvaiablePlantInfos(itemId);
            return new DataResponse(concretePlantInfos);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }


    @Log(title = "混天凝APP 全部的搅拌站信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "混天凝APP 全部的搅拌站信息", notes = "全部的搅拌站信息", produces = "application/json")
    @PostMapping("queryAllConcreteInfo")
    public DataResponse queryAllConcreteInfo(){
        try {
            List<HsmwConcretePlantInfo> concretePlantInfos = hsmwConcretePlantInfoMapper.selectList(new LambdaQueryWrapper<>());
            return new DataResponse(concretePlantInfos);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败,请联系系统管理员");
        }
    }
}
